我正在从一个Webhook接收一个json对象。我使用JSON.stringify更改为要存储在MySQL表中的字符串。稍后我从MySQL表中检索它。我在上面运行JSON.parse。然后使用数据在NodeJS中创建文本消息。当我在产品标题中用双引号引起问题。 JSON.parse在NodeJS中不喜欢它们。
我将“替换为\”。然后运行JSON.parse,效果很好,但这是手动完成的。我需要使它处于自动状态-相对于手动,让NodeJS中的代码执行此操作。
原始JSON
"line_items":[{"id":853139563,
"taxable":true,
"title":"“Fuel” Natural Fish Food - "Fuel" Natural Fish Food",
"total_discount":"0.00",
"vendor":"Aqua Design Innovations"}]
所需结果JSON-标题中的“燃料”一词现在为\“燃料\”
"line_items":[{"id":853139563,
"taxable":true,
"title":"\"Fuel\" Natural Fish Food - \"Fuel\" Natural Fish Food",
"total_discount":"0.00",
"vendor":"Aqua Design Innovations"}]
答案 0 :(得分:-1)
您可以使用Regex查找键值对的所有字符串值,然后用文字替换所有“内部”引号。
在代码结尾,我们成功地将字符串解析为JSON对象。请参阅下面的注释以获取解释:
let jsonStr = '{"line_items":[{"id":853139563, "taxable":true, "title":"“Fuel” Natural Fish Food - "Fuel" Natural Fish Food", "total_discount":"0.00", "vendor":"Aqua Design Innovations"}]}'
// this matches for all string values in the key-value pair
let strVals = jsonStr.match(/(?<=":")([^:]+?)(?="(?=,|}|]))/g) //[ '“Fuel” Natural Fish Food - "Fuel" Natural Fish Food','0.00','Aqua Design Innovations' ]
strVals.forEach(strVal => {
// we replace all quotes with literal quotes
let newVal = strVal.replace(/("|“|”)/g,'\\"');
// then replace the new value back to original string
jsonStr = jsonStr.replace(strVal,newVal);
})
console.log(jsonStr); //{"line_items":[{"id":853139563, "taxable":true, "title":"\"Fuel\" Natural Fish Food - \"Fuel\" Natural Fish Food", "total_discount":"0.00", "vendor":"Aqua Design Innovations"}]}
let json = JSON.parse(jsonStr);
console.log(json);
/*
{ line_items:
[ { id: 853139563,
taxable: true,
title: '"Fuel" Natural Fish Food - "Fuel" Natural Fish Food',
total_discount: '0.00',
vendor: 'Aqua Design Innovations' } ] }
*/
正则表达式说明:
(?=":")
向后寻找":"
模式,然后开始我们的比赛
[^:]+?
,我们一直查找直至{look}以外的任意数量的字符(:
)
(?="
向前看要结束"
,紧接着是下一个回顾
(?=,|}|])
下一个,
或}
或]
的前瞻,以确认它是值字符串的结尾