Home  >  Q&A  >  body text

javascript - About getting the name of multiple nested keys in multiple key-value pairs in json

{
  "RuntimeSources": {
    "flask-webapp": {
      "eb-flask1.3": {
        "s3url": ""
      }
    }
  },
  "DeploymentId": 4,
  "Serial": 4
}

There is such a json file. Now I need to extract the name of the key flask-webapp, which is the string itself of flask-webapp. How should I use it? Using Object.keys(), I get the three keys RuntimeSource, DeploymentId and Serial.
I feel that my description is a bit complicated. To summarize the problem is: how to extract the key in the next layer of key-value in the first key-value of this json file (it seems to be more complicated... I hope you can read it) Got it)
You can use python or javascript to implement it

ringa_leeringa_lee2686 days ago839

reply all(6)I'll reply

  • 黄舟

    黄舟2017-06-12 09:24:48

    function getFirstKeyInLevel(json, level) {
        var levelNow = 0;
        var key;
        var obj = json;
        do {
            key = Object.keys(obj)[0];
            levelNow++;
            obj = obj[key];
        } while (key && levelNow < level);
        return key;
    }
    var json = {
        'RuntimeSources': {
            'flask-webapp': {
                'eb-flask1.3': {
                    's3url': ''
                }
            }
        },
        'DeploymentId': 4,
        'Serial': 4
    };
    
    console.log(getFirstKeyInLevel(json, 1)); // RuntimeSources
    console.log(getFirstKeyInLevel(json, 2)); // flask-webapp
    console.log(getFirstKeyInLevel(json, 3)); // eb-flask1.3
    console.log(getFirstKeyInLevel(json, 4)); // s3url
    console.log(getFirstKeyInLevel(json, 5)); // undefined
    

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-12 09:24:48

    var o = {
      "RuntimeSources": {
        "flask-webapp": {
          "eb-flask1.3": {
            "s3url": ""
          }
        }
      },
      "DeploymentId": 4,
      "Serial": 4
    }

    This is the data that needs to be processed. The question of the subject should be regarded as a proper subset of the following questions
    (The problem is that as long as we obtain "flask-webapp")

    Extract all the key names of the object from the object and form an array

    This process is temporarily called flat. I have also implemented this function here to obtain this solution.

    flat(o); 
    // => 
    // ["RuntimeSources", "flask-webapp", "eb-flask1.3", "s3url", "DeploymentId", "Serial"]

    Use Object.keys to solve the problem

    Object.keys can obtain the enumerable first-level object property key names

    Use features like this to write recursive functions:

    var flat = o => {
        // 当层键名 
        if (typeof o !== 'object') return []; 
        
        var keys = Object.keys(o); 
        
        return keys.reduce((acc, cur) => {
            return acc.concat( flat(o[cur]) ); 
        }, keys); 
    }

    ScreenShot

    var log = (item, idx) => {
        console.group(`第 ${idx + 1} 个元素`)
        console.log('值:', item); 
        console.groupEnd(); 
    }
    flat(o).forEach(log); 


    Specifically you need flask-webapp this key:

    var res = flat(o).filter(e => e === 'flask-webapp'); 
    console.log(res); 
    // => 
    // ["flask-webapp"] 

    Use JSON.stringify to solve the problem

    JSON.stringify can convert objects into JSON string

    For exampleJSON.stringify(o) you can get the result
    "{"RuntimeSources":{"flask-webapp":{"eb-flask1.3":{"s3url":""}}},"DeploymentId ":4,"Serial":4}"

    Continue to observe and you will find:

    In JSON, what comes before : is the key name

    Construct the JSON elements into an array, and then pick out the ones before the colon.


    Tool function

    // 把在 str 中的 willBeReplaced 替换为 toPlace
    var replaceAll = (str, willBeReplaced, toPlace) => {
        return str.split(willBeReplaced).join(toPlace)
    }
    
    // 把在 str 的全部 willBeCut 替换成 ''
    var cut = (str, willBeCut) => {
        return replaceAll(str, willBeCut, ''); 
    }
    Implementation of

    flat

    var flat = o => {
        var str = JSON.stringify(o); 
        
        return ['{', '}', ':', ','].reduce((acc, e) => {
            return replaceAll(acc, e, ` ${e} `); 
        }, str).split(' ').filter(e => e !== "").reduce((acc, cur, idx, its) => {
            if (cur === ':'){
                acc.push(its[idx - 1]); 
            }
            
            return acc;
        }, []).map(e => cut(e, '"', ''));  
    }

    The above means:

    The first reduce adds spaces before and after { } : ,

    Corresponding code

    // o 是待处理对象 
    let str = JSON.stringify(o); 
    
    var A = ['{', '}', ':', ','].reduce((acc, e) => {
        // 把 e 的两侧都补上一个空格 
        return replaceAll(acc, e, ` ${e} `); 
    }, str)

    The result is this:

    Original str from

    "{"RuntimeSources":{"flask-webapp":{"eb-flask1.3":{"s3url":""}}},"DeploymentId":4,"Serial":4}"

    After processing, it becomes

    " { "RuntimeSources" : { "flask-webapp" : { "eb-flask1.3" : { "s3url" : "" } } } , "DeploymentId" : 4 , "Serial" : 4 } "

    Get an intermediate result A

    Next

    To be dealt with here A

    Corresponding code:

    var B = ['{', '}', ':', ','].reduce((acc, e) => {
        return replaceAll(acc, e, ` ${e} `); 
    }, str).split(' ').filter(e => e !== "")

    Convert A into intermediate array B: (from string to array)

    The last reduce gets the result

    Observe B and you can get a conclusion

    In JSON, what comes before : is the key name

    Write the final reduce accordingly: collect the elements before the colon to get the result


    ScreenShot

    reply
    0
  • 世界只因有你

    世界只因有你2017-06-12 09:24:48

    var object= {
              "RuntimeSources": {
                "flask-webapp": {
                  "eb-flask1.3": {
                    "s3url": ""
                  }
                }
              },
              "DeploymentId": 4,
              "Serial": 4
            }
        for(i in object){
            console.log(Object.keys(object[i]));
            // console.log(object[i]);//Object {flask-webapp: Object} 执行四次
            for(k in object[i]){
                console.log(Object.keys(object[i][k]));
                // console.log(object[i][k]);//Object {eb-flask1.3: Object}
                for(s in object[i][k]){
                    console.log(Object.keys(object[i][k][s]));
                    //console.log(object[i][k][s])//Object {s3url: ""}
                    for( f in object[i][k][s]){
                        console.log(Object.keys(object[i][k][f]))
                    }
                }
            }
        }
    

    The error "Cannot convert undefined or null to object" should be thrown at the end of execution. This is fine

    reply
    0
  • PHP中文网

    PHP中文网2017-06-12 09:24:48

    If you want to implement it in python, dict is a hash table structure, which means that after the data is input, it has been hashed according to the characteristics and has its own order.
    If you can specify the name of the key, you can still get it. If you can't specify it, you can still get it. The name of the key, then it can’t be done

    data = {
      "RuntimeSources": {
        "flask-webapp": {
          "eb-flask1.3": {
            "s3url": ""
          }
        }
      },
      "DeploymentId": 4,
      "Serial": 4
    }
    
    print data['RuntimeSources']['flask-webapp']
    print data['RuntimeSources'].values()[0]

    reply
    0
  • 世界只因有你

    世界只因有你2017-06-12 09:24:48

    Python’s default dictionary is unordered, but it can be implemented using the OrderedDict ordered dictionary.

    def level_keys(order_dict, level):
        _level = 1
        if level == _level:
            return order_dict.get(order_dict.keys()[0]).keys()
        else:
            return level_keys(order_dict.get(order_dict.keys()[0]), level=level - 1)
    
    
    def main(level=1):
        from collections import OrderedDict
        import json
        dict_str = """{
      "RuntimeSources": {
        "flask-webapp": {
          "eb-flask1.3": {
            "s3url": ""
          }
        }
      },
      "DeploymentId": 4,
      "Serial": 4
    }"""
        order_dict = json.loads(s=dict_str, object_pairs_hook=OrderedDict)
        print(level_keys(order_dict, level))
    
    
    if __name__ == '__main__':
        main(3)
    

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-12 09:24:48

    var json = JSON.parse('{  "RuntimeSources": {    "flask-webapp": {      "eb-flask1.3": {        "s3url": ""      }    }  },  "DeploymentId": 4,  "Serial": 4}');
    for (t in json) { console.log(t); }
    
    var test = Object.keys(json);
    console.log(test[0]);

    reply
    0
  • Cancelreply