这是原始JSON对象:
{"num":11,"content":"puss\n","percentage":0}
我想将11
替换为12
,即更改" num"的值。
{"num":12,"content":"puss\n","percentage":0}
请用Ruby语言描述。
答案 0 :(得分:7)
使用JSON#parse
将原始json字符串转换为哈希对象。根据需要更改哈希对象。然后使用JSON#dump
将其转换回json字符串:
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}'