How to iterate over this Json data in rails? - ruby-on-rails

I'm trying to Iterate over this Json data I want to get the Items out of "data I tried doing
#Response =HTTParty.get(("http://ddragon.leagueoflegends.com/cdn/5.15.1/data/en_US/item.json"))
puts #Response["data"].each do |item|
puts item
end
Also I want to be able to iterate them without having to know the IDS prior for example the first item is "1001" I don't want to have to enter those manually
but this just says that it can't find anything with '[]' for Nil:NilClass
Also before anyone mentions the JSON below doesn't finish because I only took a sample there are a lot more Items and if I were to paste it , it would easily be over 1000 Lines.
"type":"item",
"version":"5.15.1",
"basic":{},
"data":{
"1001":{
"name":"Boots of Speed",
"group":"BootsNormal",
"description":"<groupLimit>Limited to 1.</groupLimit><br><br> <unique>UNIQUE Passive - Enhanced Movement:</unique> +25 Movement Speed<br><br> <i>(Unique Passives with the same name don't stack.)</i>",
"colloq":";",
"plaintext":"Slightly increases Movement Speed",
"into":[
"3006",
"3047",
"3020",
"3158",
"3111",
"3117",
"3009"
],
"image":{
"full":"1001.png",
"sprite":"item0.png",
"group":"item",
"x":0,
"y":0,
"w":48,
"h":48
},
"gold":{
"base":325,
"purchasable":true,
"total":325,
"sell":227
},
"tags":[
"Boots"
],
"stats":{
"FlatMovementSpeedMod":25.0
}
},
"1004":{
"name":"Faerie Charm",
"description":"<stats><mana>+25% Base Mana Regen </mana></stats>",
"colloq":";",
"plaintext":"Slightly increases Mana Regen",
"into":[
"3028",
"3070",
"3073",
"3114"
],
"image":{
"full":"1004.png",
"sprite":"item0.png",
"group":"item",
"x":48,
"y":0,
"w":48,
"h":48
},
"gold":{
"base":180,
"purchasable":true,
"total":180,
"sell":126
},
"tags":[
"ManaRegen"
],
"stats":{
}
},

Four problems:
you are not parsing the response body with JSON.parse
you are using a constant name (starting with capital letter) as a variable name (#Response), you shouldn't.
unnecessary puts on iteration.
The value of data is not an array, but rather another hash. So you should iterate over it as key/value pairs.
Solution:
#response = JSON.parse(HTTParty.get(your_url).body)
#response["data"].each do |key, value|
puts key
puts value
end

I had done something like this before, maybe that can help you here is the link - Reading Json using Ruby

Related

$formatNumber outputs NaN when used in table array

I'm applying number formatting to a PDF document, which works fine in a 'parent' record in the JSON data, but fails when used inside a table. How can I get the $formatNumber expression to work inside an array of data?
The data is being merged into an invoice document, and in one of the columns of the "Invoice Line Items" I'd like to format the number with the expression $formatNumber, '#,###.00'.
Here is the merge syntax in my word document:
This formatting works fine for the parent data:
{{ $formatNumber(QuoteLineItems.totalSize, '#,###.00') }}
This formatting fails when used inside a table (the output in the PDF si "NaN")
{{ $formatNumber(QuoteLineItems.records.AmountNet, '#,###.00') }}
Image: Comparison of Success vs Failure syntax
Image: PDF Output contains NaN in table
here is the sample input data I am using inside the word plugin document tagger:
{
"QuoteLineItems":
{
"records":
[
{
"AmountGross": 47897,
"AmountNet": 44556,
"Name": "Sample Charges"
},
{
"AmountGross": 4968,
"AmountNet": 4621,
"Name": "Sample 2 Charges"
}
],
"done": true,
"totalSize": 2
},
"Name": "Sample Invoice"
}
Sorry for the delay in answering this. This is a known bug (I'm going to check on the status). For now I suggest doing your number format in your code before sending it to the API. If that doesn't make sense, let me know and I'll clarify.

Rails - Accessing JSON members

I am new to Rails, and working with some JSON, and not sure how to get to the data as the examples below:
1) If i were to use JSON.parse(response)['Response']['test']['data']['123456'], i will need to parse another response for 123457, is there a better way to loop through all the objects in data?
2) base on the membershipId, identify the top level object, ie data.
"test": {
"data": {
"123456": {
"membershipId": "321321312",
"membershipType": a,
},
"123457": {
"membershipId": "321321312",
"membershipType": a,
},
}
JSON.parse(response)['Response']['test']['data'].each do |key, object|
puts key
puts object['membershipID']
...
end
To select the data record associated with a particular membership
match_membership = '321321312'
member = JSON.parse(response)['Response']['test']['data'].select |_key, object|
object['membershipID'] == match_membership
end
puts member.key
=> 123456
For 1:
Assumption:
By you saying "need to parse another response", you were doing something like below:
# bad code: because you are parsing `response` multiple times
JSON.parse(response)['Response']['test']['data']['123456']
JSON.parse(response)['Response']['test']['data']['123457']
then simply:
Solution 1:
If you are gonna be accessing 2+ level deep hash values for just maybe 2 or 3 times,
response_hash = JSON.parse(response)
response_hash['Response']['test']['data']['123456']
response_hash['Response']['test']['data']['123457']
Solution 2:
If you are gonna be accessing 2+ level deep hash values for loooooots of times,
response_hash = JSON.parse(response)
response_hash_response_test_data = response_hash['Response']['test']['data']
response_hash_response_test_data['123456']
response_hash_response_test_data['123457']
response_hash_response_test_data['123458']
response_hash_response_test_data['123459']
response_hash_response_test_data['123460']
# ...
Solution 2 is better than Solution 1 because it saves repetitive method calls for Hash#[] which is the "getter" method each time you do like ...['test'] then ['data'] then ['123456'], and so is better-off doing Solution 2 which you store the nested-level of the hash into a variable (this does not duplicate the values in-memory!). Plus it's more readable this way.

Dart Angular Components - How to get full path of selected values?

I'm implementing a Single Selection Nested Tree from the Angular Components Example and the example code gets the selected value.
I want to get the full path with the selected value as well as the selected parent groups titles.
Is this possible? I've been searching for an API documentation but haven't found one yet.
Example:
<material-tree
[options]="nestedOptions"
[expandAll]="expandAll"
[selection]="singleSelection">
</material-tree>
-
final SelectionOptions nestedOptions = new _NestedSelectionOptions([
new OptionGroup(
['Animated Feature Films', 'Live-Action Films', 'Documentary Films'])
], {
'Animated Feature Films': [
new OptionGroup([
'Cinderalla',
'Alice In Wonderland',
'Peter Pan',
'Lady and the Tramp',
])
],
'Live-Action Films': [
new OptionGroup(
['Treasure Island', 'The Littlest Outlaw', 'Old Yeller', 'Star Wars'])
],
'Documentary Films': [
new OptionGroup(['Frank and Ollie', 'Sacred Planet'])
],
'Star Wars': [
new OptionGroup(['By George Lucas'])
],
'By George Lucas': [
new OptionGroup(
['A New Hope', 'Empire Strikes Back', 'Return of the Jedi'])
]
});
There isn't a built in way to display the path information. To make that work you would want to create a class for your values that stores the parent information and makes that accessible. Then use an ItemRenderer to ensure it is displayed as a string when used in the Material Tree.

executing code dynamically in groovy

I am trying to run code dynamically in groovy. I have someNode[0], which is the value, in variable var1
I then added double quotes to it like this
var2 = "\""+var1+"\""
then I tried to run this
request.abc."$var2"=Value
I saw here that something of this sort can be done on properties and methods. But the above code is not working. Giving me error
An error occurred [Cannot set property '"someNode[0]"' on null object], see error log for details
Any help is appreciated. Thanks.
Edit
Heres a snippet of my request
{
"app":{
"bundle":"531323947",
"cat":[
"IAB1",
"IAB9",
"IAB9-30",
"entertainment",
"games"
],
"id":"agltb3B1Yi1pbmNyDAsSA0FwcBitsL4UDA",
.
.
The field I am trying to manipulate is cat[0], which is IAB1 (I just used abc and someNode[0] in the code that i wrote above but actually they are app and cat[0])
Also, I parsed the request with jsonslurper befor running the above code
Thank you for your help
One way to do this, is by Eval
def request =[
"app":[
"bundle":"531323947",
"cat":[
"IAB1",
"IAB9",
"IAB9-30",
"entertainment",
"games"
],
]
]
assert request.app.cat[0]=='IAB1'
def var = 'request.app.cat[0]'
Eval.me('request', request, "$var = 'new value'")
assert request.app.cat[0]=='new value'
You are accessing/updating values from a map and a list. The request.app node will be a map, the request.app.cat node will be a list. Getting and setting the values in a map can be done in many different ways:
Use the put & get methods directly.
Use brackets [].
Use missing properties as map keys (i.e. the way you are using it).
For what you want to achieve, i.e. to access values from variable keys, it is much easier to use method 1 or 2 instead of method 3 with a variable inside a GString.
Example using brackets:
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
def request = new JsonSlurper().parseText '''{
"app":{
"bundle":"531323947",
"cat":[
"IAB1",
"IAB9",
"IAB9-30",
"entertainment",
"games"
],
"id":"agltb3B1Yi1pbmNyDAsSA0FwcBitsL4UDA"
}
}'''
def level0 = 'app'
def level1 = 'cat'
def node = request[level0][level1]
assert request instanceof Map
assert node instanceof List
assert node[0] == 'IAB1'
node[0] = 'new value'
assert node[0] == 'new value'
println new JsonBuilder(request).toPrettyString()
Output:
{
"app": {
"cat": [
"new value",
"IAB9",
"IAB9-30",
"entertainment",
"games"
],
"id": "agltb3B1Yi1pbmNyDAsSA0FwcBitsL4UDA",
"bundle": "531323947"
}
}

Dust.js - iterate through an iterated anonymous array

I have this data structure in dust:
{ 'items' : [
[ 'apples', "$1.00" , "Delicious" ],
[ 'oranges', "$2.00" , "Juicy" ],
]
}
I'm trying to access the inner items, and can't figure out how.
I can address the entire array of the current loop via {.} , but i can't seem to access the items within it. ( I could do this in Mustache )
I was expecting something like this to work...
{#items}
<b>{.[0]}</b> <em>only {.[1]}!</em>
<p>{.[2]}</p>
{/items}
When I ran your example in the dust playground: http://linkedin.github.io/dustjs/test/test.html
the output I got was:
<b>apples</b> <em>only $1.00!</em><p>Delicious</p><b>oranges</b> <em>only $2.00!</em><p>Juicy</p>
This looks to be what you were expecting. I believe fixes in this area after your post likely made this work. Grab the latest version of dust.

Resources