如何检测node.js中两个json字符串之间的差异 [英] How to detect differences between two json string in node.js

查看:373
本文介绍了如何检测node.js中两个json字符串之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个Json字符串在某个时间点可能有不同的值,我想知道是否可以使用JS比较它们?



对于实例,

我有两个Json字符串

I Have Two Json Strings that might have different values at some point of time , and I want to know if is it possible to compare them using JS?

For Instance,
I have these Two Json strings

//First Json
var Json1 = {"Name":"ABC";"Work":"Programmer";State:"123"};

//Second Json
var Json2 = {"Name":"XYZ";"Work":"Engineer";State:"456"};

在这里,我想要如下输出:

Here, I want output like below:

Name value changed from 'ABC' to 'XYZ'
Work value changed from 'Programmer' to 'Engineer'
State value changed from '123' to '456'





我的尝试:



不能找到解决方案。你能帮忙吗?



What I have tried:

Not able to find the solution. Can you please help here?

推荐答案

首先,你所拥有的是无效的JSON。您使用分号而不是逗号。同样在JSON字符串中,所有键都必须用引号括起来(在您的示例中不是这种情况)。



您的第一个代码步骤是转换使用 JSON.parse 的对象的JSON字符串。然后你可以使用 Object.keys 来获取第一个对象的所有键,你可以遍历这些键来查看两个对象中值的差异。

Firstly, what you have is not valid JSON. You use semicolons instead of commas. Also in a JSON string, all keys have to be surrounded by quotes (which is not the case in your example).

Your first code step would be to convert the JSON string to an object, using JSON.parse. Then you can use Object.keys to get all keys from the first object, and you can loop over these keys to see the difference in values in the two objects.
var jsonString1 = '{"Name":"ABC","Work":"Programmer","State":"123"}';
var jsonString2 = '{"Name":"XYZ","Work":"Engineer","State":"456"}';

var jsonObject1 = JSON.parse(jsonString1);
var jsonObject2 = JSON.parse(jsonString2);

var keys = Object.keys(jsonObject1);
for (var i = 0; i < keys.length; i++) {
  var key = keys[i];
  if (jsonObject1[key] != jsonObject2[key]) {
    console.log(key + " value changed from '" + jsonObject1[key] + "' to '" + jsonObject2[key] + "'");
  }
}


这篇关于如何检测node.js中两个json字符串之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆