How to parse data in JSON format?

后端 未结 5 1628
梦谈多话
梦谈多话 2020-11-21 07:12

My project is currently receiving a JSON message in python which I need to get bits of information out of. For the purposes of this, let\'s set it to some simple JSON in a s

相关标签:
5条回答
  • 2020-11-21 07:47

    Sometimes your json is not a string. For example if you are getting a json from a url like this:

    j = urllib2.urlopen('http://site.com/data.json')
    

    you will need to use json.load, not json.loads:

    j_obj = json.load(j)
    

    (it is easy to forget: the 's' is for 'string')

    0 讨论(0)
  • 2020-11-21 07:51

    Very simple:

    import json
    data = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
    print data['two']
    
    0 讨论(0)
  • 2020-11-21 07:51

    For URL or file, use json.load(). For string with .json content, use json.loads().

    #! /usr/bin/python
    
    import json
    # from pprint import pprint
    
    json_file = 'my_cube.json'
    cube = '1'
    
    with open(json_file) as json_data:
        data = json.load(json_data)
    
    # pprint(data)
    
    print "Dimension: ", data['cubes'][cube]['dim']
    print "Measures:  ", data['cubes'][cube]['meas']
    
    0 讨论(0)
  • Following is simple example that may help you:

    json_string = """
    {
        "pk": 1, 
        "fa": "cc.ee", 
        "fb": {
            "fc": "", 
            "fd_id": "12345"
        }
    }"""
    
    import json
    data = json.loads(json_string)
    if data["fa"] == "cc.ee":
        data["fb"]["new_key"] = "cc.ee was present!"
    
    print json.dumps(data)
    

    The output for the above code will be:

    {"pk": 1, "fb": {"new_key": "cc.ee was present!", "fd_id": "12345", 
     "fc": ""}, "fa": "cc.ee"}
    

    Note that you can set the ident argument of dump to print it like so (for example,when using print json.dumps(data , indent=4)):

    {
        "pk": 1, 
        "fb": {
            "new_key": "cc.ee was present!", 
            "fd_id": "12345", 
            "fc": ""
        }, 
        "fa": "cc.ee"
    }
    
    0 讨论(0)
  • 2020-11-21 08:05

    Can use either json or ast python modules:

    Using json :
    =============
    
    import json
    jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
    json_data = json.loads(jsonStr)
    print(f"json_data: {json_data}")
    print(f"json_data['two']: {json_data['two']}")
    
    Output:
    json_data: {'one': '1', 'two': '2', 'three': '3'}
    json_data['two']: 2
    
    
    
    
    Using ast:
    ==========
    
    import ast
    jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
    json_dict = ast.literal_eval(jsonStr)
    print(f"json_dict: {json_dict}")
    print(f"json_dict['two']: {json_dict['two']}")
    
    Output:
    json_dict: {'one': '1', 'two': '2', 'three': '3'}
    json_dict['two']: 2
    
    0 讨论(0)
提交回复
热议问题