我有两个JSON文件。
File1
{
"dataSet": "w28h46c7XUD",
"completeDate": "2018-10-23T14:16:11.384+0000",
"period": "2018Q3",
"orgUnit": "tBl4WduwWRw",
"dataValues": [
{
"dataElement": "QRMyfx7WQKa",
"period": "2018Q3",
"orgUnit": "zndtyhyYuh6",
"categoryOptionCombo": "gGhClrV5odI",
"attributeOptionCombo": "gGhClrV5odI",
"value": "90",
"storedBy": "biostatwakiso",
"created": "2018-10-25T14:52:26.835+0000",
"lastUpdated": "2018-10-25T14:52:26.835+0000",
"followUp": false
},
{
"dataElement": "btM76ubdLKE",
"period": "2018Q3",
"orgUnit": "Uuv34dh6Hjd",
"categoryOptionCombo": "Bbb6ZmzRhtO",
"attributeOptionCombo": "gGhClrV5odI",
"value": "7",
"storedBy": "HMISWAKISO",
"created": "2018-10-11T08:58:32.046+0000",
"lastUpdated": "2018-10-11T08:58:32.046+0000",
"followUp": false
},
{
"dataElement": "VCYHJu3BxpN",
"period": "2018Q3",
"orgUnit": "PYudhikuj23",
"categoryOptionCombo": "RbnGbnNxoJF",
"attributeOptionCombo": "gGhClrV5odI",
"value": "3",
"storedBy": "biostatwakiso2018",
"created": "2018-10-11T08:58:12.787+0000",
"lastUpdated": "2018-10-23T14:00:17.703+0000",
"followUp": false
},
...
File2
{"tBl4WduwWRw" : "ert678dDvk"},
{"zndtyhyYuh6" : "tY67UhdJj8"},
{"Uuv34dh6Hjd" : "O0plYhdjyj"},
{"PYudhikuj23" : "H67JuyghkN"},
我要实现的是一个脚本,该脚本在file1中找到键“ orgUnit”的值,并将其替换为在file2中与其匹配的键的值。 例如。在file1中找到键orgUnit = tBl4WduwWRw的值,并将其替换为file2中的ert678dDvk。
答案 0 :(得分:1)
如果您想使用自己的代码而不是使用任何库或可用函数。只是一小段代码,让我们看一下:
function handleObject(object, replaceValues) {
var values = Object.values(object);
var keys = Object.keys(object);
for (var i=0; i<values.length; i++) {
object[keys[i]] = handleReplaceOneValue(values[i], replaceValues);
}
return object;
}
function handleArray(array, replaceValues) {
for (var i=0; i<array.length; i++) {
array[i] = handleReplaceOneValue(array[i], replaceValues);
}
return array;
}
function handleReplaceOneValue(value, replaceValues) {
if (Array.isArray(value)) {
return handleArray(value, replaceValues)
}
if (value instanceof Object) {
return handleObject(value, replaceValues)
}
return replaceValues[value] ? replaceValues[value] : value;
}
然后致电:
handleObject(YourJSONFile1, YourJSONFile2);