Code
JSON object key Regex
In JSON, every object key is a double-quoted string followed by a colon. This pattern finds those keys and captures the text between the quotes, while correctly stepping over escaped characters such as \" so a quote inside the key does not end the match early. Because it requires the colon, string values in arrays and on the right side of a pair are skipped. It is useful for quick key inventories in large files, log lines that embed JSON and editor search-and-replace. It does not track nesting, so it cannot tell you which object a key belongs to. Parse the JSON for anything structural.
Pattern (JavaScript)
/"((?:[^"\\]|\\.)*)"\s*:/Matches the character """, then a group ((any character except "\\ OR the character "\", then any character), zero or more times), then the character """, then a whitespace character (space, tab, newline), zero or more times, then the character ":".
Examples
Matches
- ✓ {"name": "Ali Test"}
- ✓ "user_id":42
- ✓ { "say \"hi\"" : true }
Does not match
- ✗ {name: "x"}
- ✗ ["a", "b"]
- ✗ "value"
- ✗ {'single': 1}
Try it
3 matches (JavaScript engine)
{"name": "Ali Test"} "user_id":42 { "say \"hi\"" : true } {name: "x"} ["a", "b"] "value" {'single': 1}
Code in 8 languages
Converted automatically from the JavaScript pattern; language-specific notes are shown where the syntax or support differs.
JavaScript
const re = /"((?:[^"\\]|\\.)*)"\s*:/g;
const text = "{\"name\": \"Ali Test\"}";
const matches = [...text.matchAll(re)].map((m) => m[0]);
console.log(matches);Python
import re
pattern = re.compile(r'"((?:[^"\\]|\\.)*)"\s*:')
text = '{"name": "Ali Test"}'
matches = [m.group(0) for m in pattern.finditer(text)]
print(matches)PHP
<?php
$pattern = '/"((?:[^"\\\]|\\\.)*)"\s*:/';
$text = '{"name": "Ali Test"}';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("\"((?:[^\"\\\\]|\\\\.)*)\"\\s*:");
String text = "{\"name\": \"Ali Test\"}";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}Go
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`"((?:[^"\\]|\\.)*)"\s*:`)
text := "{\"name\": \"Ali Test\"}"
fmt.Println(re.FindAllString(text, -1))
}C#
using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"""((?:[^""\\]|\\.)*)""\s*:");
var text = "{\"name\": \"Ali Test\"}";
foreach (Match m in pattern.Matches(text))
{
Console.WriteLine(m.Value);
}Rust
// Cargo.toml: regex = "1"
use regex::Regex;
fn main() {
let re = Regex::new(r#""((?:[^"\\]|\\.)*)"\s*:"#).unwrap();
let text = "{\"name\": \"Ali Test\"}";
for m in re.find_iter(text) {
println!("{}", m.as_str());
}
}- Add regex = "1" under [dependencies] in Cargo.toml.
Ruby
pattern = /"((?:[^"\\]|\\.)*)"\s*:/
text = '{"name": "Ali Test"}'
matches = text.to_enum(:scan, pattern).map { Regexp.last_match[0] }
p matchesFrequently asked questions
- How does the pattern handle escaped quotes?
- The alternation (?:[^"\\]|\\.) consumes either a normal character or a backslash plus the next character. An escaped quote is eaten as a pair, so only an unescaped quote can close the key.
- Will it match single-quoted keys?
- No. JSON only allows double-quoted strings, so single quotes are rejected. JavaScript object literals with single quotes or bare keys are a different syntax.
- Can I rename keys with this pattern?
- You can, with a replace call and the g flag, but values that happen to contain a quote followed by a colon may be touched too. Parsing, renaming and re-serialising is safer for important data.