[removed] Find key and its value in JSON

后端 未结 5 601
暖寄归人
暖寄归人 2021-01-14 01:12

I have a JSON object that is returned in different ways, but always has key. How can I get it?

E.g.

\"Records\": {
    \"key\": \"112\"
         


        
5条回答
  •  感情败类
    2021-01-14 01:35

    I think this migth be solution (asuming key is always string and you don't care about res of data)

    const data = [`"Records": { 
        "test": {
            "test2": [
                {
                    "key": "334",
    				"key": "3343"
                }
            ]
        }
    }`, `"Records": { 
        "test": {
            "key": "512"
        }
    }`, `"Records": {
        "key": "112"
    }`]
    
    const getKeys = data => {
      const keys = []
      const regex = /"key"\s*:\s*"(.*)"/g
      let temp
      while(temp = regex.exec(data)){
        keys.push(temp[1])
      }
      return keys
    }
    
    for(let json of data){
      console.log(getKeys(json))
    }

提交回复
热议问题