我正在从包含双引号的api调用获取数据。例如data = '{"firstName":""John""}'
如何将这些数据解析为json。
预期输出:result = JSON.parse(data)
和result.firstname
的输出应为"John"
而不是John
答案 0 :(得分:1)
@Cid指出,这是无效的JSON。
您需要先对其进行消毒:-
var json = data.replace(/""/g, '"');
var x = JSON.parse(json);
如果要保留内引号,则需要使用以下内容:-
var json = data.replace(/(\".*\":)\"\"(.*)\"\"/g, '$1 "\\"$2\\""');
var x = JSON.parse(json);
但是,如果正则表达式与其他参数冲突,则可能需要弄弄它。
您可以在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)
替换文本中的$1
和$2
对应于正则表达式中的捕获组。有关详细信息,请参见String.prototype.replace()。
答案 1 :(得分:0)
尝试一下
var json = '{"firstName":""John""}'; //Let's say you got this
json = json.replace(/\"([^(\")"]+)\":/g,"$1:"); //This will remove all the quotes
json;