实际代码:
{
"workbookInformation": {
"version": "9.1",
"source-platform": "win"
},
"datasources": {
"filename": "data",
"caption": "Title",
"version": "qqq.1",
"cleaning": "no",
"inline": "true",
"validate": "no",
"class": "excel-direct",
"interpretationMode": "0"
}
}
我需要的输出:
{
"workbookInformation": {
"version": "9.1",
"source-platform": "win"
},
"Title": {
"filename": "data",
"caption": "Title",
"version": "qqq.1",
"cleaning": "no",
"inline": "true",
"validate": "no",
"class": "excel-direct",
"interpretationMode": "0"
}
}
caption
键值即。 Title
需要替换为datasources
。
答案 0 :(得分:0)
您可以使用Object.defineProperty()直接在对象上定义新属性,并将定义的属性的描述符传递给此方法,结果为Object.getOwnPropertyDescriptor():
var obj = {"workbookInformation": {"version": "9.1","source-platform": "win"},"datasources": {"filename": "data","caption": "Title","version": "qqq.1","cleaning": "no","inline": "true","validate": "no","class": "excel-direct","interpretationMode": "0"}};
Object.defineProperty(obj, 'Title', Object.getOwnPropertyDescriptor(obj, 'datasources'));
delete obj.datasources;
console.log(obj);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:-1)
根据您的示例,您只需在根JSON上添加一个带有“Title”键的新项目,然后删除带有“datasources”键的那个项目。
假设json_obj
为你的json对象:
json_obj[json_obj.datasources.caption] = json_obj.datasources;
delete(json_obj.datasources);
答案 2 :(得分:-1)
将JSON字符串解析为Javascript对象,以便您可以轻松地修改它。
jsObj = JSON.parse(jsonData);
下面我用所需的键创建一个新对象,最后再次序列化。
jsonData = JSON.stringify({
workbookInformation: jsObj.workbookInformation,
Title: jsObj.datasources,
});