mamesaye mamesaye - 2 months ago 9
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":"bob@compagny.com","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"
end
end


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

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"]}"
end  

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.

Comments