JS:如何使用替换将字符串转换为 JSON 格式,然后使用 JSON.Parse

JS: How to convert string to JSON Format using replace and then JSON.Parse

我在将字符串转换为 JSON 格式时遇到问题。

我有这种特殊的字符串:

{Object1=Text Goes Right Here, and Here, Object2 = Another Text Here}

我想把它转换成这样的

{"Object1":"Text Goes Right Here, and Here", "Object2":"Another Text Here"}

谁能帮我弄清楚如何正确转换它。

我尝试使用 replaceAll 但它总是在逗号处中断。

str.replaceAll('=', '":"').replaceAll(', ', '", "').replaceAll('{', '{"').replaceAll('}', '"}')

结果变成了这样。

{"Object1":"Text Goes Right Here", "and Here", "Object2":"Another Text Here"}

我也试过正则表达式,但它没有替换实际的字符串。

/[^[a-zA-Z]+, [a-zA-Z]+":$']/g

正则表达式或任何可以提供帮助的东西都可以。提前致谢!

我为您制作了一个丑陋的脚本来解决丑陋的问题...;)

let string = "{Object1=Text Goes Right Here, and Here, Object2 = Another Text Here}";

let stringSplitted = string.replace(/[\{\}]/g,"").split("=")
console.log("=== Step #1")
console.log(stringSplitted)

let keys = []
let values = []
stringSplitted.forEach(function(item){
  item = item.trim()
  keys.push(item.split(" ").slice(-1).join(" "))
  values.push(item.split(" ").slice(0,-1).join(" "))
})
console.log("=== Step #2")
console.log(keys, values)

keys.pop()
values.shift()
console.log("=== Step #3")
console.log(keys, values)

let result = {}
keys.forEach(function(key, index){
  result[key] = values[index]
})
console.log("=== Result")
console.log(result)

使用正向先行

https://regex101.com/r/iCPrsp/2

const str = '{Object1=Text Goes Right Here, and Here, Object2 = Another Text Here}'

const res = str
  .replaceAll(/,\s*(?=[^,]*=)/g, '", "')
  .replaceAll(/\s*=\s*/g, '":"')
  .replaceAll('{', '{"')
  .replaceAll('}', '"}')

console.log(JSON.parse(res))