Python: converting a list of dictionaries to json

前端 未结 4 1026
陌清茗
陌清茗 2020-12-08 03:54

I have a list of dictionaries, looking some thing like this:

list = [{\'id\': 123, \'data\': \'qwerty\', \'indices\': [1,10]}, {\'id\': 345, \'data\': \'mnbv         


        
相关标签:
4条回答
  • 2020-12-08 04:28

    use json library

    import json
    json.dumps(list)
    

    by the way, you might consider changing variable list to another name, list is the builtin function for a list creation, you may get some unexpected behaviours or some buggy code if you don't change the variable name.

    0 讨论(0)
  • 2020-12-08 04:38

    To convert it to a single dictionary with some decided keys value, you can use the code below.

    data = ListOfDict.copy()
    PrecedingText = "Obs_"
    ListOfDictAsDict = {}
    for i in range(len(data)):
        ListOfDictAsDict[PrecedingText + str(i)] = data[i]
    
    0 讨论(0)
  • 2020-12-08 04:41
    import json
    
    list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]
    

    Write to json File:

    with open('/home/ubuntu/test.json', 'w') as fout:
        json.dump(list , fout)
    

    Read Json file:

    with open(r"/home/ubuntu/test.json", "r") as read_file:
        data = json.load(read_file)
    print(data)
    #list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]
    
    0 讨论(0)
  • 2020-12-08 04:46
    response_json = ("{ \"response_json\":" + str(list_of_dict)+ "}").replace("\'","\"")
    response_json = json.dumps(response_json)
    response_json = json.loads(response_json)
    
    0 讨论(0)
提交回复
热议问题