从路径构造JSON

时间:2014-01-03 06:38:22

标签: javascript json node.js

我有一个JSON文档:

{
    Customer: {
        Name: "ddd",
        Address: [
            {Line1: "ABC", zip: [{d:"aa"},{d:"hh"} ,{d:"kk"}]},
            {Line1: "XYZ", zip: [{d:"gg"},{d:"ff"}]}
        ]
    }
}

我想要

的值
[
    "Customer.Address.0.Line1",
    "Customer.Address.0.zip.0.d",
    "Customer.Address.0.zip.1.d",
    "Customer.Address.1.Line1",
    "Customer.Address.1.zip.0.d",
    "Customer.Address.1.zip.1.d"
]

修改为新格式,如下所示

{
    Entity: [
        {d:"aa", Line1:ABC},
        {d:"hh", Line1:ABC},
        {d:"kk", Line1:ABC},
        {d:"gg", Line1:XYZ},
        {d:"ff", Line1:XYZ}
    ]
}

我实际上需要以下数据

{
    "Entity.0.d":"aa",
    "Entity.0.Line1":"ABC",
    "Entity.1.d":"hh",
    "Entity.1.Line1":"ABC",
    "Entity.2.d":"kk",
    "Entity.2.Line1":"ABC",
    "Entity.3.d":"gg",
    "Entity.3.Line1":"XYZ",
    "Entity.4.d":"ff",
    "Entity.4.Line1":"XYZ"
}

我需要找到路径以便我可以重建JSON。 我该怎么做?

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

var newJSON = new Object();
var keyArray = [];
for (var i=0; i< Customer.Address.length; i++){
    for (var j=0; j< Customer.Address[i].zip.length; j++){
        var innerJSON = new Object();
        innerJSON.d = Customer.Address[i].zip[j].d;
        innerJSON.Line1 = Customer.Address[i].Line1;
        keyArray.push(innerJSON);
    }
}

newJSON.key = keyArray;
console.log(JSON.stringify(newJSON)); //This line creates your new JSON string

当然我假设您在第一个JSON字符串上使用了JSON.parse:)

答案 1 :(得分:0)

您可以使用dotty

var dotty = require("dotty");

var object = {
  a: {
    b: {
      x: "y",
    },
    c: {
      x: "z",
    },
  },
};

console.log(dotty.exists(object, "a.b.x")); // true
console.log(dotty.exists(object, ["a", "b", "x"])); // true
console.log(dotty.exists(object, "a.b.z")); // false
console.log(dotty.exists(object, ["a", "b", "z"])); // false

console.log(dotty.get(object, "a.b.x")); // "y"
console.log(dotty.get(object, ["a", "b", "x"])); // "y"
console.log(dotty.get(object, "a.b.z")); // undefined
console.log(dotty.get(object, ["a", "b", "z"])); // undefine