gla*_*kou 6 ruby json ruby-on-rails
假设我们有以下描述Person的JSON对象:
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address":
{
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber":
[
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
Run Code Online (Sandbox Code Playgroud)
}
有人可以建议在Rails 3中操作前一个对象的最优雅和最有效的方法吗?
我希望能够:
提前致谢.
PS.我更喜欢在Controller中操作它!
key*_*one 25
只是解析它并改变它
hash = JSON.parse(json_data)
hash["firstname"] = "John"
hash.delete("lastname")
new_json = hash.to_json
Run Code Online (Sandbox Code Playgroud)
PS JSON.parse可能不起作用 - 它取决于您正在使用的JSON库.试试这个:
ActiveSupport::JSON.decode(json_data)
Run Code Online (Sandbox Code Playgroud)