You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用正则表达式仅替换JSON值的双引号为单引号(适配含数组的JSON场景)

Solution for Replacing Value Quotes in JSON Strings (Including Arrays)

Got it, let's tackle this problem. Your original regex works great for simple key-value pairs but misses string values inside arrays—since those elements aren't preceded by a colon, your lookbehind doesn't catch them. Here's how to fix it:

The Updated Regex

This regex handles both top-level string values and array elements:

/(?<=:|\[|,)\s*&quot;((?:\\.|[^&quot;])*?)&quot;/g

How It Works

Let's break down the key parts to understand why this works:

  • (?<=:|\[|,): Positive lookbehind that targets positions right after a colon (for key-value pairs), an opening square bracket (start of an array), or a comma (separating array elements). This covers every spot a string value can appear in your target format.
  • \s*: Optional whitespace to account for cases like [ "lion" or , "zebra" where spaces might exist around array elements.
  • &quot;: Matches the opening double quote entity.
  • ((?:\\.|[^&quot;])*?): Captures the content inside the quotes, including escaped characters (like \" if they were present in your string) using a non-greedy quantifier to avoid matching across multiple quotes.
  • &quot;: Matches the closing double quote entity.

Usage Example (JavaScript)

Since you're working with raw string operations, here's how you'd apply this in code:

const originalJsonStr = '{ &quot;id&quot;:&quot;123&quot;, &quot;name&quot;:&quot;myZoo&quot;, &quot;ticketPrice&quot;:66.5, &quot;animals&quot;:[&quot;lion&quot;,&quot;zebra&quot;,&quot;wolf&quot;] }';
const modifiedJsonStr = originalJsonStr.replace(/(?<=:|\[|,)\s*&quot;((?:\\.|[^&quot;])*?)&quot;/g, "'$1'");

console.log(modifiedJsonStr);

Result

This will output exactly the format your legacy database requires:

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

Quick Note

This solution assumes your JSON doesn't have nested objects (which aligns with your example). If you ever need to handle nested structures, you'd need a more robust approach—but for your current use case, this regex should work flawlessly.

内容的提问来源于stack exchange,提问作者Shaked

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 15:12:35