简体   繁体   English

如何用正则表达式用单引号替换 JSON 值双引号

[英]How to replace JSON values double quotes with single quotes with Regex

I use an old legacy framework that connects to a non-relational DB that can only receive a JSON string like this:我使用一个旧的遗留框架,它连接到一个只能接收 JSON 字符串的非关系数据库,如下所示:

'{
"id":'123',
"name":'myZoo',
"ticketPrice":66.5,
"animals":['lion','zebra','wolf']
}'

I have this JSON string:我有这个 JSON 字符串:

'{
"id":"123",
"name":"myZoo",
"ticketPrice":66.5,
"animals":["lion","zebra","wolf"]
}'

Using regex, I want to replace double quotes " with single quotes ' of the JSON values only ( the keys must have double quotes ).使用正则表达式,我只想用 JSON 值'单引号替换双引号" (键必须有双引号)。

the reason I want to use regex is because my framework cant handle JSON so I need to use it as string.我想使用正则表达式的原因是因为我的框架无法处理 JSON 所以我需要将它用作字符串。

For a JSON without arrays I have this code:对于没有 arrays 的 JSON 我有这个代码:

/(?<=:)"((?:\\.|[^\\])*?)"/g

But, I cant make it work with arrays.但是,我不能让它与 arrays 一起工作。

So I think what you mean by saying it doesn't work with arrays is the case of the "animals" key.所以我认为你说它不适用于 arrays 的意思是"animals"键的情况。 Could you just check if the JSON value is an array then use apply your regex to each individual element in the array then build a new array with your new elements?您能否检查 JSON 值是否是一个数组,然后使用您的正则表达式将您的正则表达式应用于数组中的每个单独元素,然后用您的新元素构建一个新数组?

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

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