Possible Duplicate:
Parsing a JSON string in ruby
Is it possible to convert a JSON string into a Ruby object? I would like to access its information with an expression similar to:
drawer.stations.tv.header
JSON string:
{ "drawer" : { "stations" : { "tv" : { "header" : "TV Channels", "logos" : { "one" : "www1", "two" : "www2", "three" : "www3" } } } } }
We can have duplicate keys in a JSON object, and it would still be valid.
You cannot have duplicate key in a dictionary. Duplicate keys in JSON aren't covered by the spec and can lead to undefined behavior (see this question). If you read the JSON into a Python dict, the information will be lost, since Python dict keys must be unique.
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
You will need to convert the JSON to Java Objects and then perform the duplicate removal operation. Added code snippet for each of the steps. Hope this helps! You will need to convert the JSON to Java Objects and then perform the duplicate removal operation.
You can parse the string into a ruby hash and then turn it into a Mash. Mash provides you with method-like access.
require 'json' require 'hashie' hash = JSON.parse json_string obj = Hashie::Mash.new hash obj.drawer.stations.tv.header # => "TV Channels"
You can also do it without a 3rd party gem, using ruby's own OpenStruct
:
require 'ostruct' require 'json' obj = JSON.parse(json_string, object_class: OpenStruct) obj.drawer.stations.tv.header # => "TV Channels"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With