Python: Decode和Encode JSON
import json, dumps encode数据,loads decode数据。
def DecodingJson(json_file):
dic = {}
jfile = open(json_file)
while True:
line = jfile.readline()
if len(line) == 0:
break
decode_file = json.loads(line)
for key, value in decode_file.items():
dic[key] = value
jfile.close()
return dic
def EncodingJson(filename, data):
out_json_file = open(filename,"w")
json_data = json.dumps(data, sort_keys = True)
out_json_file.truncate()
out_json_file.write(json_data)
out_json_file.close()
本文介绍了如何使用 Python 的 json 模块进行 JSON 数据的编码与解码操作。通过两个函数实现了 JSON 文件的读取及数据写入。首先定义了一个解码函数 DecodingJson,用于从指定文件中逐行读取 JSON 数据并将其转换为 Python 字典。其次定义了 EncodingJson 函数,用于将 Python 数据结构编码为 JSON 格式并写入文件。
1221

被折叠的 条评论
为什么被折叠?



