mamesaye mamesaye - 1 year ago 71
JSON Question

ruby array of json object access a value

I have an array of json object called line:

[{"label":"Name","value":"Bob","identifier":"field2","type":"oneLineText","page":1,"page_name":"Step 1","width":"100%"},{"label":"Email","value":"","identifier":"field3","type":"email","page":1,"page_name":"Step 1","width":"100%"},{"label":"Phone Number","value":"","identifier":"field7","type":"oneLineText","page":1,"page_name":"Step 1","width":"100%"},{"label":"Comments","value":"some information about the compagny","identifier":"field5","type":"textarea","page":1,"page_name":"Step 1","width":"100%"}]

How do i access the value of label comment :

"label":"Comments","value":"some information about the compagny"

Here is my code:

data = JSON.parse(line)
data.each do |key, value|
puts "#{key}"
puts "#{key} name: #{value["name"]}"
puts "#{key} value: #{value["value"]}\n"
label = value["name"]
value = value["value"]
if (label eq "label") && (value eq "Comments")
puts "#{key} value: #{value["value"]}\n"

I got an error after first object id parsed:

{"label"=>"Name", "value"=>"Bob", "identifier"=>"field2", "type"=>"oneLineText", "page"=>1, "page_name"=>"Step 1", "width"=>"100%"}
undefined method `[]' for nil:NilClass (NoMethodError)`

Answer Source

You can access you data using the following code:

data = JSON.parse(line) 
data.each do |d|
  puts "#{d}"
  puts "#{d} label: #{d["label"]}"
  puts "#{d} value: #{d["value"]}"

After parsing the line with JSON.parse your data variable will contain an array of hashes. When you iterate over this array , the block variable d is assigned to one of these hashes.

So, the first call to puts in this example will show the entire hash assigned to the variable d, and the second one will show the entire hash followed by the value assigned to the key label of that hash.

Similarly, the third line shows how to access the value stored in the value key.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download