簡體   English   中英

如何獲得一個帶有其父節點的json對象?

[英]How to get a piece of an json object with its parent node?

我如何才能獲得對象的一部分,包括其父節點?

完整的字符串對象:

var big = '{ "OFFLINE": { "more"  : "content"  }, 
             "ONLINE":  { "more1" : "content1" },
             "EXTRA":   { "more2" : "content2" }  }';
alert( JSON.parse( big ) );

我想進入一個新對象:

var part = '{ "OFFLINE": { "more"  : "content"  }}';

我沒有成功: JSON.parse( big ).OFFLINE

因為它包含: '{ "more" : "content" }'

而不是'{ "OFFLINE": { "more" : "content" }}'

您現在擁有的代碼JSON.parse( big ).OFFLINE正是您所需要的,您只需要將其包裝在父對象中即可,如果那是您需要的方式:

var obj = {
    OFFLINE: JSON.parse(big).OFFLINE
};

小提琴的例子

JSON.stringify將對象轉換為字符串。 嘗試這個:

 var big = '{ "OFFLINE": { "more" : "content" }, "ONLINE": { "more1" : "content1" },"EXTRA": { "more2" : "content2" } }'; var newObject = { OFFLINE: JSON.parse(big).OFFLINE } alert(JSON.stringify(newObject)); 

暫無
暫無

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

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