解析带有转义双引号的字符串到JSON对象

时间:2018-03-09 14:53:33

标签: javascript json

我有一个形式为

的json字符串



let inputStr  = '{ "name" : "some string \" with double quotes"}';
console.log(JSON.parse(inputStr));




我希望创建一个JSON对象,但它提供Unexpected token w

我尝试将\"替换为\\",但无法正常工作。

我怎么能

  • \"替换为\\"
  • 使用该字符串创建对象

实际代码

我正在解析一个包含JSON对象的文件,每行一个。试图将其转换为CSV。

这是我的变换流代码

const myTransform = new Transform({
    transform(chunk, encoding, done) {
    const vals = chunk.toString().split("\n");
    done(
      null,
      vals
        .filter(val => val && val !== "")
        .map(val=>JSON.parse(val)
        .map(val=> [val.name,val.body].join(','))

文件内容

{"body":"Davey Crockett playing his fiddle and harmonizing with the Mexican Army band playing \"deguello\" outside the Alamo. TheMexicans then hold off their daily bombardment of the Alamo out of respect for his courage. Almost certainly never happened in real life but it sure is a badass scene in my opinion. That whole movie was.", "name": "xyz"}

其中很少包含如上所示的转义双引号

2 个答案:

答案 0 :(得分:0)

您可以先使用\来转义\,然后将其转到JSON.parse()

例如:

JSON.parse('{"name":"some string with \\\" escaped double quotes"}')

答案 1 :(得分:0)

我已将您的示例转换为以下代码。出于演示目的,我将JSON文本放入DOM元素,而不是外部文件,但代码背后的原理是相同的。它运行没有错误。转义双引号没有问题。

const val = document.getElementById('fake-external-file').value;

console.log(JSON.parse(val));
<textarea id="fake-external-file" cols="80" rows="5">
{"body":"Davey Crockett playing his fiddle and harmonizing with the Mexican Army band playing \"deguello\" outside the Alamo. TheMexicans then hold off their daily bombardment of the Alamo out of respect for his courage. Almost certainly never happened in real life but it sure is a badass scene in my opinion. That whole movie was.", "name": "xyz"}
</textarea>

(从技术上讲,这不是一个真正的答案,但我不能在评论中嵌入代码片段。)