简体   繁体   English

如何使用javascript在json中用子值替换或更新键?

[英]How can i replace or update the key with child value in json using javascript?

Actual Code:实际代码:

{
    "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"
    }
}

Output I need :我需要的输出:

{
    "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 key value ie. caption键值即。 Title needs to be replaced with datasources . Title需要替换为datasources

You can define a new property directly on an object with Object.defineProperty() and pass descriptor for the property being defined to this method with the result of Object.getOwnPropertyDescriptor() :您可以使用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; }

Based on your example, you can simply add a new item on the root JSON with the key "Title" and then remove the one with the key "datasources".根据您的示例,您可以简单地在根 JSON 上添加一个键为“Title”的新项,然后删除键为“datasources”的项。

Assuming json_obj as your json object:假设json_obj作为您的 json 对象:

json_obj[json_obj.datasources.caption] = json_obj.datasources;
delete(json_obj.datasources);

Parse the JSON string into a Javascript object so that you can modify it with ease.将 JSON 字符串解析为 Javascript 对象,以便您可以轻松修改它。

jsObj = JSON.parse(jsonData);

Below I'm creating a new object with the desired keys and finally serialize it again.下面我用所需的键创建一个新对象,最后再次序列化它。

jsonData = JSON.stringify({
  workbookInformation: jsObj.workbookInformation,
  Title: jsObj.datasources,
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM