My JSON array is structured like this:
{"data":[{"Chris":[{"long":10,"lat":19}]},{"Scott":[{"long":9,"lat":18}]}]}
In the ruby program, I am wanting to be able to edit the lat and long values for the names. But I am not quite sure how to do so.
sections.each do |user_coords|
user_coords.each do |user, coords|
if user == Usrname then
#Change lat and long value for Usrname
end
end
end
How can this be done?
This is how to access individual elements in your JSON:
You can simplify the path somewhat, by using a variable as a placeholder into the object:
chris
points to the "Chris" hash, which is embedded inside thefoo
hash. Changes to thechris
hash occur insidefoo
.If the hash was defined normally, it'd be more clean/clear and straightforward:
foo
is more clearly defined as:Conditionally iterating over the hash to find a particular key/value pair looks like this with your hash:
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:
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:
Add to that any other hash elements you want:
merge!
addsbob_hash
tofoo['data']
. Then, tell the hash to output its JSON representation usingto_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.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.