2

I have a string received from a database call as follows:

"[{'url':'https://www.example.com/','category':'popular'},{'url':'https://example2.com/','category':'new'}]"

I would like to parse the string into a typescript/JS array so that it is as follows:

[
   {'url':'https://www.example.com/','category':'popular'}, 
   {'url':'https://example2.com/','category':'new'}
]

How can I go about doing this? JSON.parse won't work as the string does not resemble a stringified JSON. Thanks!

0

2 Answers 2

4

Assuming there are no strings in it containing ', you can replace all occurrences of the single quote with double quotes, then you can parse it:

const str = "[{'url':'https://www.example.com/','category':'popular'},{'url':'https://example2.com/','category':'new'}]";

const arr = JSON.parse(str.replace(/'/g,'"'));

console.log(arr);

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

2 Comments

Just curious: What would you do to handle inner ' characters? Say you have "Joe's Bar" in one of the fields.
@kol: Then the regex would have to get a lot more complex, as it would have to consider word boundaries, or look for single quotes next to JSON "delimiters" like []{}:,
1

Replace single quotes with double quotes then JSON.parse

JSON.parse(
"[{'url':'https://www.example.com/','category':'popular'},{'url':'https://example2.com/','category':'new'}]"
.replace(/\'/g, '"')
)

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.