我需要使用 node.js 从 javascript 文件中提取对象。我能够读取 javascript 文件,还能够对需要转换为对象的字符串进行切片。这是我的代码。
const AboutLocale = function() {
return {
person: {
name: "zxczv",
age: 25,
gender: "male",
},
ar: true,
};
};
我只想要此文件中的 person 对象,并且我可以使用切片运算符来实现此目的。现在它给了我一个看起来像这样的字符串
"{
name: "man",
age: 25,
gender: "male",
}"
我尝试解析它,但它不是有效的 JSON。我需要帮助将其转换为有效的对象。
最佳答案
您可以使用一些正则表达式来完成此操作。第一个将所有属性名称替换为自身,但引用了。第二个删除右括号之前的所有逗号。请注意,这是一个非常脆弱的解决方案,如果您向它抛出任何意外的东西,它可能会崩溃。最好只运行该文件,运行命令 AboutLocale,然后将输出 JSON.stringify 为有效的 JSON。
const input = `{
name: "man",
age: 25,
gender: "male",
}`
const input2 = `{header:"Aboutjdkahsfjk34",productShortName:"OBDX123456",version:"Version",servicePack:"Service Pack",poweredByValue:"asag",copyright:"Copyright 2006-2020",build:"Build",name:"manav"}`
const input3 = `{header:"Aboutjdka,hsfjk34",productShortName:"OBDX1,23456",version:"Version",servicePack:"Service Pack",poweredByValue:"asag",copyright:"Copyright 2006-2020",build:"Build",name:"manav"}`
fixed = input.replace(/\b(.*?):/g, "\"$1\":").replace(/,.*\n.*}/gm, "}")
fixed2 = input2.replace(/([,{])(.*?):/g, "$1\"$2\":")
let fixed3 = ""
let inAProperty = false
input3.split("").forEach((e,i) => {
if (e === "{") fixed3 += "{\""
else if (e === ":") fixed3 += "\":"
else if (e === ",") fixed3 += inAProperty ? e : ",\""
else if (e === "\"") {
inAProperty = !inAProperty
fixed3 += e
} else fixed3 += e
})
console.log(fixed)
console.log(JSON.parse(fixed))
console.log(fixed2)
console.log(JSON.parse(fixed2))
console.log(fixed3)
console.log(JSON.parse(fixed3))
关于javascript - 将字符串转换为有效的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60694886/