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

如何用PHP为JSON字符串中的变量名(如file、label)添加双引号?

Fix Unquoted JSON Keys with Regex (Newbie-Friendly Solution)

Hey there! I totally get the frustration of dealing with those half-baked JSON strings where keys are missing double quotes—been there, done that as a newbie figuring out valid JSON. Let's break down a simple regex solution to fix this for you.

The Regex & Replacement Logic

We need to target all key names (like file, label) that are immediately followed by a colon : and wrap them in double quotes. Here's the regex to use:

Regex Pattern: (\w+)(?=:)
Replacement String: "$1"

Let me break this down so you understand what's happening:

  • (\w+): This captures one or more alphanumeric characters (letters, numbers) or underscores—exactly the kind of characters most JSON keys use. The parentheses mark this as a "captured group" we can reuse in the replacement.
  • (?=:): This is a "positive lookahead"—it makes sure the captured key is directly followed by a colon, so we don't accidentally match random words in your string values.
  • The replacement "$1" takes the captured key (from group 1) and wraps it in double quotes.

Example Code (JavaScript)

Here's how you'd use this in a real-world scenario—this works in most programming languages with regex support (Python, PHP, etc., just adjust the syntax slightly):

// Your original messy string
const original = '{file:"File_Name.mp3"},{file:"File_Name.mp4",label:"720"},{file:"File_Name.mp4",label:"360"}';

// Apply the regex replacement
const fixedJSON = original.replace(/(\w+)(?=:)/g, '"$1"');

console.log(fixedJSON);
// Output: {"file":"File_Name.mp3"},{"file":"File_Name.mp4","label":"720"},{"file":"File_Name.mp4","label":"360"}

Important Notes for Newbies

  • This basic regex works for simple keys (letters, numbers, underscores). If your keys have special characters like hyphens (my-key) or spaces, you'll need to tweak the regex to ([^\s:"{},]+)(?=:)—this matches any character that isn't whitespace, quotes, colons, braces, or commas before a colon.
  • Watch out for colons inside your string values! For example, if you have {file:"note: this is a file"}, the basic regex will incorrectly wrap note in quotes. If you run into this edge case, let me know and we can adjust the regex to ignore content inside existing double quotes.

Hope this fixes your problem—happy coding!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:51:55