gpt4 book ai didi

javascript - 解析字符串并删除空格和换行符并转换为 json OBJECT

转载 作者:行者123 更新时间:2023-11-28 06:28:16 25 4
gpt4 key购买 nike

我有一个字符串,通过以下方式我如何将此字符串转换为 JSON 对象..我的字符串是

{\"Warranty\": [ \n { \n \"Name\": \"test\", \n \"Type\": \"test2\", \n \"Months\": \"6\", \n }, \n { \n \"Name\": \"Test6\", \n \"Type\": \"test7\", \n \"Months\": \"6\", \n }, \n { \n \"Name\": \"test9\", \n \"Type\": \"test10\", \n \"Miles\": \"10000\", \n } \n ]}

请帮忙将上面的字符串转换为 JSON 对象。

我尝试使用以下代码,但仍然得到字符串值而不是对象

  var body = " {\"Warranty\": [ \n { \n \"Name\": \"test\", \n \"Type\": \"test2\", \n \"Months\": \"6\", \n }, \n { \n \"Name\": \"Test6\", \n \"Type\": \"test7\", \n \"Months\": \"6\", \n }, \n { \n \"Name\": \"test9\", \n \"Type\": \"test10\", \n \"Miles\": \"10000\", \n } \n ]} ".replace(/\r?\n|\r/g, "").replace(/\s+/g, "");
var json=body.replace(/['"]+/g, '');
var object = JSON.stringify(json);
object = JSON.parse(object)

最佳答案

如果(且仅当)您确定该字符串不包含邪恶部分(即您确定数据的来源及其完整性),那么使用 eval 可能是最简单的。 :

var body = " {\"Warranty\": [ \n { \n \"Name\": \"test\", \n \"Type\": \"test2\", \n \"Months\": \"6\", \n }, \n { \n \"Name\": \"Test6\", \n \"Type\": \"test7\", \n \"Months\": \"6\", \n }, \n { \n \"Name\": \"test9\", \n \"Type\": \"test10\", \n \"Miles\": \"10000\", \n } \n ]} ";
eval("var object = " + body);
console.log(object);

关于javascript - 解析字符串并删除空格和换行符并转换为 json OBJECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34926261/

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