How to parse data in JSON format?

后端 未结 5 1818
梦谈多话
梦谈多话 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:52

    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"
    }
    

提交回复
热议问题