Home > Net >  Change name of main row Rails in JSON
Change name of main row Rails in JSON

Time:05-06

So i have a json:

{
  "code": "Q0934X",
  "name": "PIDBA",
  "longlat": "POINT(23.0 33.0)",
  "altitude": 33
}

And i want to change the column code to Identifier

The wished output is this

{
  "Identifier": "Q0934X",
  "name": "PIDBA",
  "longlat": "POINT(23.0 33.0)",
  "altitude": 33
}

How can i do in the shortest way? Thanks

CodePudding user response:

It appears that both "the json" you have and your desired result are JSON strings. If the one you have is json_str you can write:

json = JSON.parse(json_str).tap { |h| h["Identifier"] = h.delete("code") }.to_json
puts json
  #=> {"name":"PIDBA","longlat":"POINT(23.0 33.0)","altitude":33,"Identifier":"Q0934X"}

Note that Hash#delete returns the value of the key being removed.

CodePudding user response:

Perhaps transform_keys is an option.

The following seems to work for me (ruby 2.6):

json = JSON.parse(json_str).transform_keys { |k| k === 'code' ? 'Identifier' : k }.to_json

But this may work for Ruby 3.0 onwards (if I've understood the docs):

json = JSON.parse(json_str).transform_keys({ 'code': 'Identifier' }).to_json
  • Related