walter walter - 4 years ago 136
Ruby Question

Change certain value of a json object


This is the raw json object

I wanna replace 11 with 12, namely change the value of "num"


Please describe it in Ruby language, thanks!

Answer Source

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}'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download