Handling JSON Objects

Suppose we have the following JSON object that describes 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 anyone suggest the most elegant and efficient way to manage a previous object in Rails 3?

I want to be able to:

  • Add another element, such as "firstname", "lastname", etc.
  • Delete existing item
  • Change an item without deleting it or adding a new one. (for example, change the name to "Nick")

Thanks in advance.

PS. I prefer to manipulate it in the controller!

+5
source share
1 answer

just analyze it and change it

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

P.S. JSON.parse - , JSON . :

ActiveSupport::JSON.decode(json_data)
+25

All Articles