js:如何使用replace和json.parse将字符串转换为json格式

lf3rwulv  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(275)

我无法将字符串转换为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"}

我还尝试了regexm,但它并没有替换实际的字符串。

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

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

ktca8awb

ktca8awb1#

使用正向前瞻
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))
czfnxgou

czfnxgou2#

我给你做了一个难看的脚本来解决一个难看的问题…;)

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)

相关问题