I'm trying to process a JSON file:
{
"features": {
"additional-options": true
},
"values": {
"lo-value": 34,
"hi-value": 554
},
"persons": [
{
"name": "john",
"member": true,
"current": false,
"sponsor": "pete",
"profile": "",
"credits": ["04"],
"linked": ["philip","guy"],
"maptools": ["crossfit","soccer","running"]
},
{
"name": "mary",
"member": true,
"current": false,
"sponsor": "judy",
"profile": "",
"credits": ["all"],
"activities": ["swimming","cycling","running"]
}
],
"data_map": [1122,3234]
}
I would like to be able to:
- Update a value on a key value pair
- Delete both the key/value
- Delete or insert a value that's an array
I have tried so many thing to get this right.
My simplified code idea is:
require 'json'
hash = JSON.parse(File.read('test.json'))
# Add key & value or change existing one
def change_key(hash, key, value)
keys = key.strip(".")
hash[*keys] = value
end
def add_to_array(hash, key, val)
keys = key.strip(".")
hash[*keys] = locate_arr(hash, key).insert(val)
end
# Delete a key and it's value
def del_key(hash, key)
keys = key.strip(".")
hash[*keys].delete[-1]
end
def del_from_array(hash, key, val)
keys = key.strip(".")
hash[*keys] = locate_arr(hash, key).delete[-1]
end
f = File.write('test.json') ; f.puts JSON.pretty_generate(hash)
change_key(hash, "features.additional-options", false)
del_from_array(hash, "persons.name=mary.activities", "cycling")
add_to_array(hash, "persons.name=mary.activities", "hockey")
del_key(hash, "data_map")
del_key(hash, persons.name=john.profile)
del_key(hash, persons.name=mary.credits)
The resulting JSON should be:
{
"features": {
"additional-options": false
},
"values": {
"lo-value": 34,
"hi-value": 554
},
"persons": [
{
"name": "john",
"member": true,
"current": false,
"sponsor": "pete",
"credits": ["04"],
"linked": ["philip","guy"],
"maptools": ["crossfit","soccer","running"]
},
{
"name": "mary",
"member": true,
"current": false,
"sponsor": "judy",
"profile": "",
"activities": ["swimming", "running","hockey"]
}
]
}
I'm not sure how to work with JSON that is structured like this.
See Question&Answers more detail:
os