CodexBloom - Programming Q&A Platform

Regex scenarios to Extract Nested JSON Objects in JavaScript Using Node.js

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
regex javascript node.js JavaScript

I need some guidance on I'm experimenting with I'm working on a project and hit a roadblock... I'm trying to extract nested JSON objects from a string using regex in a Node.js application, but it's not working as expected. The JSON strings I'm working with can have nested structures, and I'm struggling to capture them without losing data. Here's a sample of the string I'm trying to parse: ```json {"user": {"id": 1, "name": "John Doe", "address": {"city": "New York", "state": "NY"}}} ``` I want to extract the entire `user` object, including the nested `address`, but my current regex seems to unexpected result when there are multiple nested levels. My regex pattern looks like this: ```javascript const regex = /{.*?}/g; ``` When I run it, I only get the outermost braces, and it does not capture the entire nested structure. I'm getting the following output: ``` {"user": {"id": 1, "name": "John Doe"}} ``` Instead of the whole nested object. I've tried using non-greedy quantifiers as shown, but it doesn't seem sufficient for matching nested structures. Is there a better way to handle this, or should I look into a parsing library instead? Any regex pattern adjustments or alternatives that could work would be greatly appreciated! I'm using Node.js v14.17.0, and my current approach is causing data loss. I'm working on a REST API that needs to handle this. Thanks for taking the time to read this! I'm coming from a different tech stack and learning Javascript. Any help would be greatly appreciated!