如何使用正则表达式仅替换JSON值的双引号为单引号(适配含数组的JSON场景)
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*"((?:\\.|[^"])*?)"/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.": Matches the opening double quote entity.((?:\\.|[^"])*?): 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.": 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 = '{ "id":"123", "name":"myZoo", "ticketPrice":66.5, "animals":["lion","zebra","wolf"] }'; const modifiedJsonStr = originalJsonStr.replace(/(?<=:|\[|,)\s*"((?:\\.|[^"])*?)"/g, "'$1'"); console.log(modifiedJsonStr);
Result
This will output exactly the format your legacy database requires:
{ "id":'123', "name":'myZoo', "ticketPrice":66.5, "animals":['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

