修改JSON字符串,比较另一个JSON字符串

时间:2015-02-27 13:28:07

标签: ruby-on-rails ruby json ruby-on-rails-4

我正在尝试使用来自带有ruby的JSON字符串#2的给定信息来修改JSON字符串#1以下。输出应该类似于字符串#3(一个键:增加值和一个键:从字符串#2更新的值)。经过大量搜索我没有找到任何类似的解决方案如果有人知道请帮助

输入字符串#1

{   "AC01": { "state": [ {"old": "112", "new": "100"} ],
              "temp": [{"old": "12","new": "200" }] },
    "AC02": { "state": [ {"old": "12","new": "120"}],
              "temp": [ {"old": "12","new": "220"}]}
}

输入字符串#2

{   "AC01": { "state": [ { "new": "200", "time": "12212" } ] }
}

输出Json字符串应该是这样的: 字符串#3

{   "AC01": { "state": [ {"old": "100", "new": "200","time": "12212"} ],
              "temp": [{"old": "12","new": "200" }] },
    "AC02": { "state": [ {"old": "12","new": "120"}],
              "temp": [ {"old": "12","new": "220"}]}
}

1 个答案:

答案 0 :(得分:0)

使用deep_merge gem。像这样:

js1 = '{   "AC01": { "state": [ {"old": "112", "new": "100"} ],
              "temp": [{"old": "12","new": "200" }] },
           "AC02": { "state": [ {"old": "12","new": "120"}],
              "temp": [ {"old": "12","new": "220"}]}
}'
js2 = '{   "AC01": { "state": [ { "new": "200", "time": "12212" } ] } }'

require 'json'
require 'deep_merge'

obj1 = JSON.parse(js1)
obj2 = JSON.parse(js2)
p obj1.deep_merge(obj2, {:merge_hash_arrays => true}).to_json

结果是:

{
    "AC01": {
        "state": [{"old": "112","new": "100","time": "12212"}],
        "temp": [{"old": "12","new": "200"}]
    },
    "AC02": {
        "state": [{"old": "12","new": "120"}],
        "temp": [{ "old": "12","new": "220" }]
    }
}