gpt4 book ai didi

node.js - 在nodejs中转义json中的双引号

转载 作者:太空宇宙 更新时间:2023-11-03 23:57:58 24 4
gpt4 key购买 nike

我从 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 - 标题中的“Fuel”一词现在为“Fuel”

"line_items":[{"id":853139563,
"taxable":true,
"title":"\"Fuel\" Natural Fish Food - \"Fuel\" Natural Fish Food",
"total_discount":"0.00",
"vendor":"Aqua Design Innovations"}]

最佳答案

您可以使用正则表达式查找键值对的所有字符串值,然后将所有“内部”引号替换为文字。

在代码的最后,我们成功地将字符串解析为 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' } ] }
*/

正则表达式解释:

(?=":") looks behind for ":" pattern which then begins our match

[^:]+? we look for any number of characters excluding :, up till the lookahead

(?=" looks ahead to a closing " which is immediately followed by next lookahead

(?=,|}|]) next lookahead for either , or } or ] which confirms it's the end of the value string

关于node.js - 在nodejs中转义json中的双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56196174/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com