【问题标题】:Compare two nested json objects rails 3比较两个嵌套的 json 对象 rails 3
【发布时间】:2012-02-03 03:06:12
【问题描述】:

我正在使用 rails 3 并使用 act_as_tree。如何迭代嵌套的 json,以便找到两个节点之间的差异?

我想比较的json看起来像这样:

{    
    "text": "To Do",
    "children": [{
        "text": "Go jogging",
        "children":[]
    }, {
        "text": "Take a nap",
        "children":[]
    }]
 }

 {    
     "text": "To Do",
     "children": [{
         "text": "Climb Everest",
         "children":[]
     }]
 }

【问题讨论】:

标签: ruby-on-rails-3 json


【解决方案1】:

请看https://rubygems.org/gems/json-compare

有可能做一些事情来获得差异:

require 'yajl'
require 'json-compare'

json1 = File.new('spec/fixtures/twitter-search.json', 'r')
json2 = File.new('spec/fixtures/twitter-search2.json', 'r')
old, new = Yajl::Parser.parse(json1), Yajl::Parser.parse(json2)
result = JsonCompare.get_diff(old, new)

【讨论】:

    【解决方案2】:

    显示差异 - 我想您需要将 JSON 反序列化为结构,并比较对象。在我看来,这是最简单的方法。

    【讨论】:

      【解决方案3】:

      正如 OhadR 提到的,反序列化和比较对象似乎是一种可行的方法。

      为此,请查看此 gem:

      https://github.com/liufengyun/hashdiff

      它甚至有一个 online demo 比较 JSON 和 YAML 结构,并显示差异。

      【讨论】:

        猜你喜欢
        • 2020-01-17
        • 2014-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多