簡體   English   中英

從路徑構造JSON

[英]Constructing a JSON from its path

我有一個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。 我怎么做?

您可以執行以下操作:

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 :)

你可以用點滴

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM