gpt4 book ai didi

node.js - 如何在 Angular 中将字符串转换为 json?

转载 作者:太空宇宙 更新时间:2023-11-03 23:12:07 24 4
gpt4 key购买 nike

从以下类型的字符串开始:

const json = '{"list":"[{"additionalInformation": {"source": "5f645d7d94-c6ktd"}, "alarmName": "data", "description": "Validation Error. Fetching info has been skipped.", "eventTime": "2020-01-27T14:42:44.143200 UTC", "expires": 2784, "faultyResource": "Data", "name": "prisco", "severity": "Major"}]"}'

如何将其作为 JSON 进行管理?以下方法不起作用

const obj = JSON.parse(json );
unuspected result

如何正确解析它?

总之,我应该提取与第一项列表相关的部分,然后解析它包含的 JSON。

最佳答案

您的 JSON 无效。以下是 JSON 的有效版本:

const json= {
"list": [ {
"additionalInformation": {
"source": "5f645d7d94-c6ktd"
},
"alarmName": "data",
"description": "Validation Error. Fetching info has been skipped.",
"eventTime": "2020-01-27T14:42:44.143200 UTC",
"expires": 2784,
"faultyResource": "Data",
"name": "prisco",
"severity": "Major"
}
]
}

上面已经是一个 JSON,再次将其解析为 JSON 会抛出错误。

JSON.parse() 解析字符串/文本并将其转换为 JavaScript 对象。字符串/文本应采用 JSON 格式,否则会引发错误。

更新:创建一个函数来清理字符串并为 JSON.parse() 做好准备:

cleanString(str) {
str = str.replace('"[', '[');
str = str.replace(']"', ']');
return str;
}

并像这样使用它:

json = this.cleanString(json);
console.log(JSON.parse(json));

演示:

let json = '{"list":"[{"additionalInformation": {"source": "5f645d7d94-c6ktd"}, "alarmName": "data", "description": "Validation Error. Fetching info has been skipped.", "eventTime": "2020-01-27T14:42:44.143200 UTC", "expires": 2784, "faultyResource": "Data", "name": "prisco", "severity": "Major"}]"}';
json = cleanString(json);
console.log(JSON.parse(json));

function cleanString(str) {
str = str.replace('"[', '[');
str = str.replace(']"', ']');
return str;
}

关于node.js - 如何在 Angular 中将字符串转换为 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59934787/

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