问题
This is the raw JSON object:
{"num":11,"content":"puss\n","percentage":0}
I want to replace 11 with 12, namely change the value of "num".
{"num":12,"content":"puss\n","percentage":0}
Please describe it in Ruby language.
回答1:
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}'
来源:https://stackoverflow.com/questions/34454553/change-certain-value-of-a-json-object