简体   繁体   中英

How do i get a property JSON with Regular Expression in Javascript?

Hello Everyone!

My main goal is to get a list of object properties of a nested object , using method for loop is too confusing for me, and it's very simple to use Regex by using the JSON.stringify() and String.prototype.match() methods.

This is my JSON

{
    "date": 153039023841,
    "name": "VEmpink",
    "item": {
        "brand": "Apple",
        "product": "iPhone SE 2016",
        "color": "Rose Gold"
    },
    "status": {
        "type": "process",
        "dateStatus": 153092315152
    },
    "dp": 0,
    "price": 700,
    "notes": null
}

Expectation results

[
    "date",
    "name",
    "item",
    "brand",
    "product",
    "color",
    "status",
    "type",
    "dateStatus",
    "dp",
    "price",
    "notes"
]

My results with pattern /"(.*?)":/g

 var myObj = { date: 153039023841, name: "VEmpink", item: { brand: "Apple", product: "iPhone SE 2016", color: "Rose Gold" }, status: { type: "process", dateStatus: 153092315152 }, dp: 0, price: 700, notes: null }; var getKeys = JSON.stringify(myObj).match(/"(.*?)":/g); console.log(getKeys)

and also, I am a beginner in regex

Use recursion to iterate over the object and its nested objects and build a set of unique keys.

You should not parse JSON using a regular expression.

 const data = { "date": 153039023841, "name": "VEmpink", "item": { "brand": "Apple", "product": "iPhone SE 2016", "color": "Rose Gold" }, "status": { "type": "process", "dateStatus": 153092315152 }, "dp": 0, "price": 700, "notes": null }; const isObj = o => o?.constructor === Object; const grabKeys = (obj, keys=new Set()) => { if (isObj(obj)) { for (let key in obj) { keys.add(key); grabKeys(obj[key], keys); } } return keys; }; console.log([...grabKeys(data)]);
 .as-console-wrapper { top: 0; max-height: 100%;important; }

I got expected result with pattern /"(\w+)":/gi

 var myObj = { date: 153039023841, name: "VEmpink", item: { brand: "Apple", product: "iPhone SE 2016", color: "Rose Gold" }, status: { type: "process", dateStatus: 153092315152 }, dp: 0, price: 700, notes: null }; var getKeys = JSON.stringify(myObj).match(/"(\w+)":/gi); console.log(getKeys);

My problem with the pattern /"(.*?)":/g because JSON.stringify() begin " and it end "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM