Fastest way to filter json string in Python
Question: I have a json structure like

    
    
    {
        "a": "1",
        "b": "2",
        "c": {
            "d": "3"
        }
    }
    

What I want is to only keep the 1st level of the json, i.e. remove if 1st
level's value is not a string, so I have a program like

    
    
    import json
    
    s = ''' {
        "a": "1",
        "b": "2",
        "c": {
            "d": "3"
        } } '''
    
    data = json.loads(s) 
    ret = {}
    
    for k, v in data.items():
        if (isinstance(v, basestring)):
            ret[k] = v
    
    print json.dumps(ret)
    

Since I need to process huge amount of json string like that, I am looking for
if any fastest way or more elegant way to do the same thing in Python


Answer: Use a dict comprehension:

    
    
    ret = {k: v for k, v in json.loads(s).iteritems() if isinstance(v, basestring)}
    

The `dict.iteritems()` call here prevents a full list being built first.

If your JSON input is truly huge, consider switching to an iterative JSON
parser like [`ijson`](https://pypi.python.org/pypi/ijson/), and parse your
JSON with an event-driven interface:

    
    
    import ijson
    
    ret = {}
    key = None
    
    with open(some_large_jsonfile) as json_file:
        for prefix, type, value in ijson.parse(json_file):
            if prefix and not '.' in prefix and type == 'string':
                # only top-level string values
                ret[prefix] = value
    

but it could be a good idea to process the key-value pairs right there and
then rather than build up a full dictionary.

