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!

4
  • Does this answer your question? Convert JS object to JSON string Commented Jul 11, 2021 at 4:42
  • 1
    is that really what your initial string looks like? That's not valid anything. Can you show what it actually looks like? Commented Jul 11, 2021 at 4: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. Commented Jul 11, 2021 at 4:45
  • can we depend on the equal sign only happening with the assignments (Object1 = ...)? Commented Jul 11, 2021 at 4:47

2 Answers 2

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))

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for this! It is really helpful! <3
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.