-3

i want to access elements in JSON.

My JSON looks like:

{
"@odata.context":
"https://www.ccyyxxxyyy5......com.ne.de/odata/$metadata#Product(Id,Name)
/$entity","Id":1,"Name":"Build your own computer"
 }

I want only access "Id" and "Name". How can I do that? Can anybode make me an example?

r.az91
  • 41
  • 1
  • 4
  • 4
    What have you tried so far? Have you [read the documentation on JSON](http://ruby-doc.org/stdlib/libdoc/json/rdoc/JSON.html)? Have you read any [other StackoverFlow answers](http://stackoverflow.com/a/34295262/1954610) on how to parse JSON? Please see [How do I ask a good question](https://stackoverflow.com/help/how-to-ask) for advice on what to do before posting. – Tom Lord May 02 '17 at 11:54

1 Answers1

0

Suppose you json is saved in my_json, it is very much similar to hash, just that the keys are stringified. my_json[key] is the syntax to get the value of key. In your case:

my_json['Id']
#=> 1

You seem to be working with JSON array, then:

names = my_json.map { |j| j['Name'] }
#=> ["Build your own computer", ..]

Based on json body provided:

data_array = data['value']
name_at_0 = data_array[0]['Name']
name_at_1 = data_array[1]['Name']
#=> etc...
Md. Farhan Memon
  • 6,055
  • 2
  • 11
  • 36