How to parse data in JSON format?

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

提交回复
热议问题