user12551649
user12551649

Reputation: 426

How to convert array string to JSON value?

This string is received from database:

"[{\"country_code\":\"IN\",\"gdpr_fields\":{\"policy\":\"yes\",\"profiling\":\"na\",\"age\":\"yes\",\"subscription\":\"na\"}}]"

I have been trying to convert this string to a JSON value but it always ends up throwing an error

undefined:1
[{\"country_code\":\"IN\",\"gdpr_fields\":{\"policy\":\"yes\",\"profiling\":\"na\",\"age\":\"yes\",\"subscription\":\"na\"}}]
  ^
Unexpected token \ in JSON at position 2

Is there a way to convert this string to JSON using javascript?

Expected Result:

[{"country_code":"IN","gdpr_fields":{"policy":"yes","profiling":"na","age":"yes","subscription":"na"}}]

Upvotes: 0

Views: 102

Answers (3)

user15388024
user15388024

Reputation:

You can replace all \" with " with replaceAll or replace with a regex (for older browsers/engines):

const invalidJson = '[{\\"country_code\\":\\"IN\\",\\"gdpr_fields\\":{\\"policy\\":\\"yes\\",\\"profiling\\":\\"na\\",\\"age\\":\\"yes\\",\\"subscription\\":\\"na\\"}}]';

try {
  JSON.parse(invalidJson);
} catch(err) {
  console.log('Parse error');
}
const json = invalidJson.replaceAll('\\"', '\"');
console.log(JSON.parse(json));

const invalidJson = '[{\\"country_code\\":\\"IN\\",\\"gdpr_fields\\":{\\"policy\\":\\"yes\\",\\"profiling\\":\\"na\\",\\"age\\":\\"yes\\",\\"subscription\\":\\"na\\"}}]';

try {
  JSON.parse(invalidJson);
} catch(err) {
  console.log('Parse error');
}
const json = invalidJson.replace(/\\"/g, '\"');
console.log(JSON.parse(json));

Upvotes: 1

Vishal P Gothi
Vishal P Gothi

Reputation: 997

var temp = "[{\"country_code\":\"IN\",\"gdpr_fields\":{\"policy\":\"yes\",\"profiling\":\"na\",\"age\":\"yes\",\"subscription\":\"na\"}}]";   


temp = JSON.parse(temp);

console.log(temp);

Please use something like this, it is working for me.

Upvotes: 1

user12551649
user12551649

Reputation: 426

This could be only possible by first cleaning the string

jsonArr = "[{\\\"country_code\\\":\\\"IN\\\",\\\"gdpr_fields\\\":{\\\"policy\\\":\\\"yes\\\",\\\"profiling\\\":\\\"na\\\",\\\"age\\\":\\\"yes\\\",\\\"subscription\\\":\\\"na\\\"}}]".split("\\").join("")

and then

JSON.parse(jsonArr)

Upvotes: 0

Related Questions