gpt4 book ai didi

javascript - 如何重构Json

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:52:02 24 4
gpt4 key购买 nike

我目前在修改 Json 架构时遇到问题,架构如下:

{
"$schema": "www.abc.com",
"compounds": {
"schemas": {
"Run": {
"type": "object",
"properties": {
"runContext": {
"type": "object",
"properties": {
"runNumber": {
"type": "integer"
},
"conveyanceType": {
"type": "string"
}
},
"required": [
"runNumber",
"conveyanceType"
]
}
}
}
}
}
}

我知道这可以使用递归来完成,我已经尝试获取所需的项目(代码在下面),但我不知道如何将所需的项目放回属性并更改为 bool 值。提前致谢。

    private modifyJson(jsonArr: any) {
//console.log(jsonArr);
for (let i in jsonArr) {
//console.log(typeof i);
let item = jsonArr[i];
if (typeof item === "object") {
//console.log("here " + JSON.stringify(item));
this.modifyJson(item);
if (i === "required") {
console.log("here required " + JSON.stringify(item));
for (let j in item) {
//console.log(item[j]);
const required = item[j]; //fetch required item
}
}
}
}
}

我想把它变成这样的格式:

    {
"$schema": "www.abc.com",
"compounds": {
"schemas": {
"Run": {
"type": "object",
"properties": {
"runContext": {
"type": "object",
"properties": {
"runNumber": {
"type": "integer",
"required": true
},
"conveyanceType": {
"type": "string",
"required": true
}
}
}
}
}
}
}
}

最佳答案

您可以将递归函数与 for...in 循环一起使用,并在任何级别上使用 required 键更新对象。

const data = {"$schema":"www.abc.com","compounds":{"schemas":{"Run":{"type":"object","properties":{"runContext":{"type":"object","properties":{"runNumber":{"type":"integer"},"conveyanceType":{"type":"string"}},"required":["runNumber","conveyanceType"]}}}}}}

function update(obj) {
for (let prop in obj) {
if (typeof obj[prop] === 'object') update(obj[prop]);
if (prop === 'required') {
obj[prop].forEach(key => {
if (obj.properties[key]) {
obj.properties[key].required = true;
}
})

delete obj[prop]
}
}
}

update(data)
console.log(data)

关于javascript - 如何重构Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56629676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com