0

I am having trouble converting my string to JSON format.

I have this specific kind of string:

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

I wanted to convert it to something like this

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

Can anybody help me figure out how to properly convert this.

I tried using replaceAll but it keeps on breaking on the comma.

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

And it ended up like this.

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

I also tried regexm but it is not replacing the actual strings.

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

A regex or anything that could help would be fine. Thank you in advance!

Ayuk
  • 27
  • 4
  • Does this answer your question? [Convert JS object to JSON string](https://stackoverflow.com/questions/4162749/convert-js-object-to-json-string) – Kinglish Jul 11 '21 at 04:42
  • 1
    is that really what your initial string looks like? That's not valid anything. Can you show what it actually looks like? – Kinglish Jul 11 '21 at 04:43
  • @Kinglish yes, that was the actual string I am getting from the result. I find it weird but I need to find a workaround just to format my object in proper JSON format. – Ayuk Jul 11 '21 at 04:45
  • can we depend on the equal sign only happening with the assignments (Object1 = ...)? – Kinglish Jul 11 '21 at 04:47

2 Answers2

1

Using Positive Lookahead

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))
User863
  • 19,346
  • 2
  • 17
  • 41
0

I made you an ugly script to fix an ugly problem... ;)

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)
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64