Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 950
glarkou Avatar asked Jun 30 '11 12:06

glarkou


1 Answers

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)
like image 68
keymone Avatar answered Oct 21 '22 04:10

keymone