javascript - 将字符串转换为有效的 json

标签 javascript node.js json string

我需要使用 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/

相关文章:

iphone - iOS JSONKit objectWithData 返回 null

javascript - document.getElementById 变量使用 jquery 更改类的值

javascript - 主干事件触发顺序

JavaScript reduce 不能处理数学函数?

c# - EF 6 代码首先将 IEnumerable<> 转换为 Json "Self referencing loop detected with type..."

json - Groovy JSONBuilder 问题

javascript - 相同的代码在不同的 IDE 中不起作用 - html、css

javascript - CSS - 固定菜单按钮在滚动时显示

mysql - 重现 MySQL 错误 : The server closed the connection (node. js)

php - 清空 libs.css 和 libs.js 文件