Change certain value of a JSON object [duplicate]

烂漫一生 提交于 2020-05-31 06:18:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!