首页 > 解决方案 > 通过将对象放入数组来重新格式化 JSON

问题描述

我正在尝试重新格式化我的 JSON 以使用外部 API

我当前的 JSON 结构:

{
    "serviceConfigs": {
        "servicecode": "SC1",
        "specifiers": {
            "Brand ID": {
                "text": {
                    "value": "test",
                    "type": "text"
                }
            },
            "Program ID": {
                "text": {
                    "value": "test",
                    "type": "text"
                }
            }
        }
    }
}

期望的输出:

{
    "serviceConfigs": [{
        "servicecode": "SC1",
        "specifiers": {
            "Brand ID": {
                "text": {
                    "value": "test",
                    "type": "text"
                }
            },
            "Program ID": {
                "text": {
                    "value": "test",
                    "type": "text"
                }
            }
        }
    }]
}

所以目前 serviceConfigs 在一个对象中,但我希望它进入一个数组

我目前的思考过程是使用推送命令,但我不确定如何访问对象(循环?)。

标签: javascriptjsonreformatting

解决方案


您可以访问密钥的值并将其以所需格式放回相同的密钥。

let obj = {"serviceConfigs": {"servicecode": "SC1","specifiers": {"Brand ID": {"text": {"value": "test","type": "text"}},"Program ID": {"text": {"value": "test","type": "text"}}}}}

obj.serviceConfigs = [obj.serviceConfigs]

console.log(obj)


推荐阅读