allomov
11/19/2013 - 12:53 PM

Create objects from json hash, add fields to them and move them back to json.

Create objects from json hash, add fields to them and move them back to json.

require 'json'
require 'ostruct'

json = [ 
  {
    "measureUnitSymbol" => "g",
    "quantity" => 25,
    "ingredient" => {
        "name" => "Butter",
        "carbsPerHundred" => 0.6,
    }
  },
  {
    "measureUnitSymbol" => "g",
    "quantity" => 100,
    "ingredient" => {
        "name" => "Carrot",
        "carbsPerHundred" => 4.4,
    }
  }
]

json_objects = json.map {|json_hash| OpenStruct.new json_hash}

json_objects.each_with_index { |obj, i| obj.order = i + 1 }

result_hash = json_objects.map {|obj| obj.marshal_dump }.to_json

puts result_hash