I suggest to use a ruby's hash to manipulate the object data:
hashy = {
"field1": {
"display": 'abc',
"value": 'def'
},
"field2": {
"display": 'abc2'
},
"field3": {
"display": 'abc3',
"value": 'def1'
}
}
Or if it's a json string:
hashy = JSON.parse('{"field1": {"display": "abc","value": "def"},"field2": {"display": "abc2"},"field3": {"display": "abc3","value": "def1"}}')
You can try this in irb:
h[:field2][:value] ? 'value exists' : 'value don\'t exist and returns nil'
And it will return "value don't exist and returns nil"
You can set your value key with an empty value asking if the value is nil:
hashy[:field2][:value] = '' if hashy[:field2][:value].nil?
# or
hashy[:field2][:value] = '' unless hashy[:field2].has_key?(:value)
Then your hash will be:
{:field1=>{:display=>"abc", :value=>"def"}, :field2=>{:display=>"abc2", :value=>""}, :field3=>{:display=>"abc3", :value=>"def1"}}
You can parse the resulting hash into JSON
# require 'json' # Don't forget to require json
require 'json'
JSON.generate(hashy)
# or
h.to_json
# => "{\"field1\":{\"display\":\"abc\",\"value\":\"def\"},\"field2\":{\"display\":\"abc2\",\"value\":\"\"},\"field3\":{\"display\":\"abc3\",\"value\":\"def1\"}}"