Blankman
Blankman

Reputation: 267260

Convert a JSON value to another JSON shape?

I have the following JSON file that I need to transform.

Original JSON file:

{
  "configs": [ 
    {
      "ignore": "this",
      "key": "abc123",      
      "default": false
    },    
    {
      "ignore": "that",
      "key": "def123",    
      "default": "#F5F5F5"
    },
    {
      "type": "color",
      "key": "ghi123",      
      "default": "#3d4246"
    }
  ]    
}

I want to convert the JSON to look like this:

{
   "configs": [
    {
        "abc123": false
    },
    {
        "def123": "#F5F5F5"        
    },
    {
        "ghi123": "#3d4246"
    }
   ] 

}

How can I do this? require 'json'

original_json = JSON.parse("...") #original JSON shape

Upvotes: 0

Views: 96

Answers (2)

demir
demir

Reputation: 4709

With Enumerable#each_with_object you can create new hash as you want. Then you can convert it to json.

original_hash = JSON.parse(original_json)
new_hash = original_hash[:configs].each_with_object({ configs: [] }) do |item, new_hash|
  new_hash[:configs] << {
    item[:key] => item[:default]
    # add another key value pair if you want
  }
end

new_hash.to_json
#=>  {
#      "configs": [
#        {
#          "abc123": false
#        },
#        {
#          "def123": "#F5F5F5"
#        },
#        {
#          "ghi123": "#3d4246"
#        }
#      ]
#    }

Upvotes: 1

orde
orde

Reputation: 5283

There's likely a cleaner way, but here's a shot:

require 'json'

original_json = JSON.parse('{
  "configs": [ 
    {
      "ignore": "this",
      "key": "abc123",      
      "default": false
    },    
    {
      "ignore": "that",
      "key": "def123",    
      "default": "#F5F5F5"
    },
    {
      "type": "color",
      "key": "ghi123",      
      "default": "#3d4246"
    }
  ]    
}')

original_json['configs'].each do |h| 
  k = h["key"]
  v = h["default"]
  h.clear
  h[k] = v
end

original_json.to_json
#=> {"configs":[{"abc123":false},{"def123":"#F5F5F5"},{"ghi123":"#3d4246"}]}

Upvotes: 1

Related Questions