ruby 数组 json 对象访问一个值
ruby array of json object access a value
我有一个名为 line 的 json 对象数组:
[{"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%"}]
如何访问标签注释的值:
"label":"Comments","value":"some information about the compagny"
这是我的代码:
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
第一个对象 ID 解析后出现错误:
{"label"=>"Name", "value"=>"Bob", "identifier"=>"field2", "type"=>"oneLineText", "page"=>1, "page_name"=>"Step 1", "width"=>"100%"}
undefined method `[]' for nil:NilClass (NoMethodError)`
您可以使用以下代码访问您的数据:
data = JSON.parse(line)
data.each do |d|
puts "#{d}"
puts "#{d} label: #{d["label"]}"
puts "#{d} value: #{d["value"]}"
end
在用 JSON.parse
解析行后,您的 data
变量将包含一个哈希数组。当您遍历此数组时,块变量 d
被分配给这些散列之一。
因此,在此示例中对 puts
的第一次调用将显示分配给变量 d
的整个哈希,第二个将显示整个哈希后跟分配给变量的值该散列的键 label
。
同样,第三行显示了如何访问存储在 value
键中的值。
我有一个名为 line 的 json 对象数组:
[{"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%"}]
如何访问标签注释的值:
"label":"Comments","value":"some information about the compagny"
这是我的代码:
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
第一个对象 ID 解析后出现错误:
{"label"=>"Name", "value"=>"Bob", "identifier"=>"field2", "type"=>"oneLineText", "page"=>1, "page_name"=>"Step 1", "width"=>"100%"}
undefined method `[]' for nil:NilClass (NoMethodError)`
您可以使用以下代码访问您的数据:
data = JSON.parse(line)
data.each do |d|
puts "#{d}"
puts "#{d} label: #{d["label"]}"
puts "#{d} value: #{d["value"]}"
end
在用 JSON.parse
解析行后,您的 data
变量将包含一个哈希数组。当您遍历此数组时,块变量 d
被分配给这些散列之一。
因此,在此示例中对 puts
的第一次调用将显示分配给变量 d
的整个哈希,第二个将显示整个哈希后跟分配给变量的值该散列的键 label
。
同样,第三行显示了如何访问存储在 value
键中的值。