将 MultiDict 转换为正确的 JSON
在本文中,我们将了解什么是 MultiDict,以及如何在Python中将 multidict 转换为 JSON 文件。
首先,我们将 multidict 转换为字典数据类型,最后,我们将该字典转储到 JSON 文件中。
使用的功能:
- json.dump(): Python模块中的 JSON 模块提供了一个名为 dump() 的方法,它将Python对象转换为适当的 JSON 对象。它是 dumps() 方法的一个小变种。
Syntax : json.dump(d, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None)
Parameters:
indent: It improves the readability of the JSON file. The possible values that can be passed to this parameter are simply double
quotes(“”), any integer values. Simple double quotes make every key-value pair appear in a new line.
Example :
json.dump(dic,file_name, indent=4)
- 将 MultiDict 转换为正确的JSONMultiDict :这是一个存在于 multidict Python模块中的类
Syntax :
- multidict.MultiDict(**kwargs)
- multidict.MultiDict(mapping, **kwargs)
- multidict.MultiDict(iterable, **kwargs)
Return :
- It will create a mutable multidict instance.
- It has all the same functions that are available for dictionaries.
Example :
from multidict import MultiDict
dic = [(‘geeks’, 1), (‘for’,2), (‘nerds’, 3)]
multi_dict = MultiDict(dic)
代码:
Python3
# import multidict module
from multidict import MultiDict
# import json module
import json
# create multi dict
dic = [('Student.name', 'Ram'), ('Student.Age', 20),
('Student.Phone', 'xxxxxxxxxx'),
('Student.name', 'Shyam'), ('Student.Age',18),
('Student.Phone', 'yyyyyyyyyy'),
('Batch', 'A'), ('Batch_Head', 'XYZ')]
multi_dict = MultiDict(dic)
print(type(multi_dict))
print(multi_dict)
# get the required dictionary
req_dic = {}
for key, value in multi_dict.items():
# checking for any nested dictionary
l = key.split(".")
# if nested dictionary is present
if len(l) > 1:
i = l[0]
j = l[1]
if req_dic.get(i) is None:
req_dic[i] = {}
req_dic[i][j] = []
req_dic[i][j].append(value)
else:
if req_dic[i].get(j) is None:
req_dic[i][j] = []
req_dic[i][j].append(value)
else:
req_dic[i][j].append(value)
else: # if single dictonary is there
if req_dic.get(l[0]) is None:
req_dic[l[0]] = value
else:
req_dic[l[0]] = value
# save the dict in json format
with open('multidict.json', 'w') as file:
json.dump(req_dic, file, indent=4)
输出:
JSON 文件输出: