Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to convert a JSON string to an object? [duplicate]

Tags:

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"         }       }     }   } } 
like image 293
mickael Avatar asked Dec 16 '12 01:12

mickael


People also ask

Does JSON object allow duplicate keys?

We can have duplicate keys in a JSON object, and it would still be valid.

Can JSON have duplicate keys Python?

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.

Can object have duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

How do you remove duplicates from JSON in Java?

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.


1 Answers

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" 

Update

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" 
like image 168
Sergio Tulentsev Avatar answered Sep 20 '22 23:09

Sergio Tulentsev