简体   繁体   English

带有双引号的JSON数据

[英]JSON data with double quotes

I am getting data from api call which contains double quotes. 我正在从包含双引号的api调用获取数据。 for example data = '{"firstName":""John""}' 例如data = '{"firstName":""John""}'

how to parse this data into json. 如何将这些数据解析为json。 expected-output: result = JSON.parse(data) and result.firstname should give output as "John" not John 预期输出: result = JSON.parse(data)result.firstname应该将输出作为"John"而不是John

As @Cid points out, that is invalid JSON. 正如@Cid指出的那样,这是无效的JSON。

You will need to sanitize it first:- 您需要先对其进行消毒:-

var json = data.replace(/""/g, '"');

var x = JSON.parse(json);

If you want to keep the inner quotes, you'll need to use something like this:- 如果要保留内部引号,则需要使用以下内容:

var json = data.replace(/(\".*\":)\"\"(.*)\"\"/g, '$1 "\\"$2\\""');

var x = JSON.parse(json);

However, you may need to fiddle with the regex if it conflicts with other parameters. 但是,如果正则表达式与其他参数冲突,则可能需要摆弄正则表达式。

You can review the regex above at https://regex101.com/ to get an explanation of how the regex matches:- 您可以在https://regex101.com/上查看上述正则表达式,以获取正则表达式如何匹配的说明:-

/(\".*\":)\"\"(.*)\"\"/g

  1st Capturing Group (\".*\":)
    \" matches the character " literally (case sensitive)
    .* matches any character (except for line terminators)
      * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    \" matches the character " literally (case sensitive)
    : matches the character : literally (case sensitive)

  \" matches the character " literally (case sensitive)
  \" matches the character " literally (case sensitive)

  2nd Capturing Group (.*)
    .* matches any character (except for line terminators)
      * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)

  \" matches the character " literally (case sensitive)
  \" matches the character " literally (case sensitive)

Global pattern flags
g modifier: global. All matches (don't return after first match)

The $1 and $2 in the replacement text correspond to the capture groups in the regex. 替换文本中的$1$2对应于正则表达式中的捕获组。 See String.prototype.replace() for details. 有关详细信息,请参见String.prototype.replace()

Try With this 试试这个

var json = '{"firstName":""John""}';       //Let's say you got this
json = json.replace(/\"([^(\")"]+)\":/g,"$1:");  //This will remove all the quotes
json;   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM