如何获得一块json对象与它的父节点

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

本文关键字:对象 父节点 json 一块 何获得      更新时间:2023-09-26

我怎样才能得到我的对象的一部分,包括它的父节点?

完整的字符串对象:

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

我想要得到一个新对象:

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

I have no success with: JSON.parse( big ).OFFLINE

,因为它包含:'{ "more" : "content" }'

代替'{ "OFFLINE": { "more" : "content" }}'

您现在拥有的代码- JSON.parse( big ).OFFLINE正是您所需要的,您只需要将其包装在父对象中,如果这就是您需要它的方式:

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

例子小提琴

JSON。将对象转换为字符串。试试这个:

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