如何将数组字符串转换为 JSON 值?

时间:2021-07-08 10:34:36

标签: javascript json reactjs

这个字符串是从数据库接收的:

"[{\"country_code\":\"IN\",\"gdpr_fields\":{\"policy\":\"yes\",\"profiling\":\"na\",\ "年龄\":\"是\",\"订阅\":\"na\"}}]"

我一直在尝试将此字符串转换为 JSON 值,但最终总是抛出错误

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

有没有办法使用 javascript 将此字符串转换为 JSON?

预期结果:

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

3 个答案:

答案 0 :(得分:1)

您可以将所有 \" 替换为带有 "replaceAll 或带有正则表达式的 replace(对于较旧的浏览器/引擎):

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

答案 1 :(得分:0)

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


temp = JSON.parse(temp);

console.log(temp);

请使用这样的东西,它对我有用。

答案 2 :(得分:-1)

这只能通过先清理字符串才能实现

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

然后

JSON.parse(jsonArr)