CodexBloom - Programming Q&A Platform

Regex scenarios to Match Complex JSON Key Patterns in JavaScript - implementing Nested Structures

šŸ‘€ Views: 88 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-09
regex javascript json JavaScript

I'm having trouble extracting specific key-value pairs from a JSON-like string using regex in JavaScript... The goal is to match keys that follow a specific pattern, but I keep running into issues, especially with nested structures. Here's a simplified version of the JSON I'm dealing with: ```json { "user": { "name": "John Doe", "age": 30, "details": { "hobbies": ["reading", "gaming"], "location": "New York" } }, "admin": { "accessLevel": "full", "permissions": ["read", "write", "delete"] } } ``` I want to extract the keys that start with `"user."` and are followed by a specific pattern, such as `"user.name"` and `"user.age"`. I tried the following regex: ```javascript const jsonString = '{ "user": { "name": "John Doe", "age": 30, "details": { "hobbies": ["reading", "gaming"], "location": "New York" } }, "admin": { "accessLevel": "full", "permissions": ["read", "write", "delete"] } } }'; const regex = /"user\.(\w+)"/g; let matches; while ((matches = regex.exec(jsonString)) !== null) { console.log(matches[1]); } ``` However, the output only gives me the first match and then returns null without processing the rest. I suspect it might be due to how I'm defining the regex pattern, but I’m not quite sure what the correct approach is. Additionally, I noticed that the regex fails when there are nested structures and arrays. Can anyone advise how to correctly match these keys while ensuring all relevant pairs are captured? I'm using Node.js v14.17.0. Thank you! The project is a web app built with Javascript.