1

I have an url for JSON object which look like thaht :

{
 "sitesSessions" : {
   "910360_2" : {
    "name": "name",
    "adresse": "adresse"
   },
   "76590_1" : {
    "name": "name",
    "adresse": "adresse"
   }
 }
}

(this is just an example, the real JSON object is very long) and I want to access to "name" and "adresse" in this object.

I need to create a rake task that parse all the document and take name and adresse and insert these in an excel file.

But I don't know how to access to "name" and "adresse" because I have this "910360_2" or "76590_1" that are different for each object in the json ...

Does someone could help me ?

2 Answers 2

2

It's very easy, I suggest you read Ruby Hashes.

{
 "sitesSessions" : {
   "910360_2" : {
    "name": "name",
    "adresse": "adresse"
   },
   "76590_1" : {
    "name": "name",
    "adresse": "adresse"
   }
 }
}
>> require 'json'
=> true
>> JSON.parse(f)
=> {"sitesSessions"=>{"910360_2"=>{"name"=>"name", "adresse"=>"adresse"}, "76590_1"=>{"name"=>"name", "adresse"=>"adresse"}}}
>> JSON.parse(f)["sitesSessions"].values
=> [{"name"=>"name", "adresse"=>"adresse"}, {"name"=>"name", "adresse"=>"adresse"}]
>> JSON.parse(f)["sitesSessions"].values.map do |x|
>>   [x['name'], x['adresse']]
>> end
=> [["name", "adresse"], ["name", "adresse"]]
Sign up to request clarification or add additional context in comments.

Comments

1

It looks like you could just iterate return all values in the hash:

hash = JSON.parse(json)
hash['sitesSessions'].values
#=> [
#     {
#       "name": "name",
#       "adresse": "adresse"
#     },
#     {
#       "name": "name",
#       "adresse": "adresse"
#     }
#   ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.