1

I am getting this string from my api call:

"{'attachments': [{'type': 'html', 'html': 'text-test'}, {'type': 'album', 'album': [{'url': 'htps://s3.eu-central-8f7ba8d118dbf1/pic/cdyegkwkaije7720e2f72.jpg', 'type': 'image'}]}]}"

I need to find a way to parse it and be able to iterate over the items in attachments list, but when I try to run JSON.parse(str) I am getting an error, I guess because the word attachments has commas around it.

The error is Uncaught SyntaxError: Unexpected token ' in JSON at position 1 at JSON.parse

How can I decode it to be able to reach the attachments?

1
  • 5
    well JSON requires " and all your properties and values use ' so your api is returning invalid JSON. Commented May 5, 2022 at 17:44

2 Answers 2

1

you have to replace ' with " . try this

var jsonStr ="{'attachments': [{'type': ..." //your api string

jsonStr = jsonStr.replaceAll("'","\"");
var result = JSON.parse(jsonStr);
Sign up to request clarification or add additional context in comments.

Comments

1

JSON requires ", not '. If this is your own API, you should change the implementation to return " quotations. Best to use JSON.stringify(objectDataToSend) if your API is written in JavaScript.

If this is not your own API, I'd suggest using the String.replaceAll() function to replace all ' with ":

let data = "{'attachments': [{'type': 'html', 'html': 'text-test'}, {'type': 'album', 'album': [{'url': 'htps://s3.eu-central-8f7ba8d118dbf1/pic/cdyegkwkaije7720e2f72.jpg', 'type': 'image'}]}]}"

const result = JSON.parse(data.replaceAll("'", '"'));

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.