JSON对象数组与JSON数组的比较

时间:2016-04-20 07:12:39

标签: json comparison jsonobject

我在通用提取物对象夹具中面临问题。

我的服务层为我提供了类似这样的东西。它是值的数组/列表

[{"id":1,"description":"Anti-takeover Provision"},
{"id":2,"description":"Capital Structure"},  
{"id":3,"description":"Director"},
{"id":4,"description":"Equity Plan"},
{"id":5,"description":"Executive Compensation"},
{"id":6,"description":"General Governance"},
{"id":7,"description":"Merger or Acquisition"},
{"id":12,"description":"Other"},
{"id":8,"description":"Proxy Contest"},
{"id":9,"description":"Reincorporation"},
{"id":10,"description":"Shareholder Proposal"},
{"id":11,"description":"Shareholder Rights"}]

但是我的数据库json

{"document":[{"VALUE":"Anti-takeover Provision","TOPIC_ID":1},
{"VALUE":"Capital Structure","TOPIC_ID":2},
{"VALUE":"Director","TOPIC_ID":3},
{"VALUE":"Equity Plan","TOPIC_ID":4},
{"VALUE":"Executive Compensation","TOPIC_ID":5},
{"VALUE":"General Governance","TOPIC_ID":6},
{"VALUE":"Merger or Acquisition","TOPIC_ID":7},
{"VALUE":"Other","TOPIC_ID":12},
{"VALUE":"Proxy Contest","TOPIC_ID":8},
{"VALUE":"Reincorporation","TOPIC_ID":9},
{"VALUE":"Shareholder Proposal","TOPIC_ID":10},
{"VALUE":"Shareholder Rights","TOPIC_ID":11}]}

我如何轻松比较这两个值?

1 个答案:

答案 0 :(得分:0)

  1. 检查长度是否相同

  2. Sort the two lists按相应的ID字段

  3. 检查值是否匹配

    // stop as soon as you find a difference
    
    for(i=0; i < listLength; i++) {
    
        if (listA[i].id != listB[i].TOPIC_ID) { return false; }
    
        if (listA[i].description != listB[i].VALUE) { return false; }
    }
    
    // if you get here, they must be the same
    
    return true;