Editing JSON Array Contents in Ruby

Editing JSON Array contents in Ruby

This is how to access individual elements in your JSON:

require 'json'

foo = JSON['{"data":[{"Chris":[{"long":10,"lat":19}]},{"Scott":[{"long":9,"lat":18}]}]}']
foo['data'][0]['Chris'][0]['long'] = 5
foo['data'][0]['Chris'][0]['lat'] = 7
foo # => {"data"=>[{"Chris"=>[{"long"=>5, "lat"=>7}]}, {"Scott"=>[{"long"=>9, "lat"=>18}]}]}

You can simplify the path somewhat, by using a variable as a placeholder into the object:

foo = JSON['{"data":[{"Chris":[{"long":10,"lat":19}]},{"Scott":[{"long":9,"lat":18}]}]}']
chris = foo['data'][0]['Chris'][0]
chris['long'] = 5
chris['lat'] = 7
foo # => {"data"=>[{"Chris"=>[{"long"=>5, "lat"=>7}]}, {"Scott"=>[{"long"=>9, "lat"=>18}]}]}

chris points to the "Chris" hash, which is embedded inside the foo hash. Changes to the chris hash occur inside foo.

If the hash was defined normally, it'd be more clean/clear and straightforward:

foo = JSON['{"data":{"Chris":{"long":5,"lat":7},"Scott":{"long":9,"lat":18}}}']
foo['data']['Chris']['long'] = 5
foo['data']['Chris']['lat'] = 7
foo # => {"data"=>{"Chris"=>{"long"=>5, "lat"=>7}, "Scott"=>{"long"=>9, "lat"=>18}}}

foo is more clearly defined as:

foo = {
'data' => {
'Chris' => {'long' => 5, 'lat' => 7},
'Scott' => {'long' => 9, 'lat' => 18}
}
}

Conditionally iterating over the hash to find a particular key/value pair looks like this with your hash:

require 'json'

foo = JSON['{"data":[{"Chris":[{"long":10,"lat":19}]},{"Scott":[{"long":9,"lat":18}]}]}']

user_name = 'Chris'
data = foo['data'].first
data.first.each do |key, value|
if key == user_name
data[user_name].first['long'] = 5
data[user_name].first['lat'] = 6
end
end

foo # => {"data"=>[{"Chris"=>[{"long"=>5, "lat"=>6}]}, {"Scott"=>[{"long"=>9, "lat"=>18}]}]}

Having to use first (or [0]) to get at hash elements has smell to it.

Using a hash that is defined correctly results in code that looks like:

foo = JSON['{"data":{"Chris":{"long":10,"lat":19},"Scott":{"long":9,"lat":18}}}']
foo['data'].each do |key, value|
if key == user_name
value['long'] = 5
value['lat'] = 7
end
end
foo # => {"data"=>{"Chris"=>{"long"=>5, "lat"=>7}, "Scott"=>{"long"=>9, "lat"=>18}}}

How can I add another person called Bob with long = 10 and lat = 20

It sounds like you don't have a good grasp of manipulating/accessing hashes, or how to convert to/from JSON. You'd do well to get those basics down.

Don't start with JSON, instead, start with a Ruby hash:

require 'json'

foo = {
"data" => {
"Chris" => {
"long" => 5,
"lat" => 7
},
"Scott" => {
"long" => 9,
"lat" => 18
}
}
}

Add to that any other hash elements you want:

bob_hash = {'Bob' => {'long' => 10, 'lat' => 20}}
foo['data'].merge!(bob_hash)

merge! adds bob_hash to foo['data']. Then, tell the hash to output its JSON representation using to_json. It's a lot easier to work with familiar Ruby structures, and let Ruby do the heavy-lifting of converting to JSON, than it is to try to do string manipulation on an existing JSON string. If you have the JSON, then parse it and convert/modify the resulting Ruby object, then output the JSON again.

puts foo.to_json
# >> {"data":{"Chris":{"long":5,"lat":7},"Scott":{"long":9,"lat":18},"Bob":{"long":10,"lat":20}}}

I'd recommend reading "How to convert JSON to a hash, search for and change a value" also, as it's a useful alternative for accessing values in the resulting hash.

Change certain value of a JSON object

Convert the raw json string into hash object using JSON#parse. Change the hash object as you want. Then convert it back to json string using JSON#dump:

require 'json'

raw_json = '{"num":11,"content":"puss\n","percentage":0}'
h = JSON.parse(raw_json)
h['num'] += 1
JSON.dump(h) # => '{"num":12,"content":"puss\n","percentage":0}'

How can I add custom value to json array in response in ruby?

You could try something like this:

render json: {"message": "somevalue", "response": response}

Simple as that, should do the trick.

By the way, you can also call the "response" field whatever you want. It's gonna be the key of the object you get in JSON later.

Appending to Json Array in ruby on rails

This should work for you:

render json: User.all.to_json(include: :tags)

or alternatively (just tag names):

render json: User.all.to_json(methods: :tag_list)

Appending to JSON array in Ruby

First convert the JSON to a Ruby hash this way:

require 'json'
rb_hash = JSON.parse('<your json>');
rb_hash["data"] << { name: "John", long: 20, lat: 45 }

rb_hash.to_json

How do I access JSON array data?

JSON#parse should help you with this

require 'json'

json = '[ { "attributes": {
"id": "usdeur",
"code": 4
},
"name": "USD/EUR"
},
{ "attributes": {
"id": "eurgbp",
"code": 5
},
"name": "EUR/GBP"
}]'

ids = JSON.parse(json).map{|hash| hash['attributes']['id'] }
#=> ["usdeur", "eurgbp"]

JSON#parse turns a jSON response into a Hash then just use standard Hash methods for access.



Related Topics



Leave a reply



Submit