开发者

JSON object manipulation

Let's suppose that we have the following JSON Object that describes a Person:

{
 "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"
     }
 ]

}

Can someone suggest the most elegant and most efficient way to manipulate the previous object in Rails 3?

I want to be able to:

  1. Add another element like "firstname","lastname", etc .
  2. Remove an existing element
  3. Change an element without removing it or adding a new one. (eg. change firstname to "Nick")

Thanks in advance.

PS. I prefer to manipulate it in the Controller!


just parse it and change it

hash = JSON.parse(json_data)
hash["firstname"] = "John"
hash.delete("lastname")
new_json = hash.to_json

P.S. JSON.parse might not work - it depends on which JSON library you're using. try this instead:

ActiveSupport::JSON.decode(json_data)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜