使用python将数据写入json文件
使用以下python代码:使用python将数据写入json文件,json,python-3.x,Json,Python 3.x,使用以下python代码: import fnmatch import os import json data = [] for file in os.listdir('./images'): if fnmatch.fnmatch(file, '*.jpg'): data.append(file) with open('asd.json', 'w') as f: json.dump({'da
import fnmatch
import os
import json
data = []
for file in os.listdir('./images'):
if fnmatch.fnmatch(file, '*.jpg'):
data.append(file)
with open('asd.json', 'w') as f:
json.dump({'data' : {"name": data}},f,sort_keys = True, indent = 4,
ensure_ascii = False)
我在文件asd.json
中获得以下json输出:
{
"data": {
"name": [
"got01.jpg",
"got02.jpg"
]
}
}
但是我希望我的json输出在asd.json
as中:
{
"data": [
{
"name": "got01.jpg"
},
{
"name": "got02.jpg"
}
]
}
您能推荐一种更好的方法以获得所需结构的输出吗?试试看
json.dump({'data':[{“name”:x}表示数据中的x]},f,sort\u keys=True,indent=4,确保\u ascii=False)
完整代码:
import fnmatch
import os
import json
data = []
for file in os.listdir('./images'):
if fnmatch.fnmatch(file, '*.jpg'):
data.append(file)
with open('asd.json', 'w') as f:
json.dump({'data' : [{"name": x} for x in data]},f,sort_keys = True, indent = 4,
ensure_ascii = False)
试一试
json.dump({'data':[{“name”:x}表示数据中的x]},f,sort\u keys=True,indent=4,确保\u ascii=False)
完整代码:
import fnmatch
import os
import json
data = []
for file in os.listdir('./images'):
if fnmatch.fnmatch(file, '*.jpg'):
data.append(file)
with open('asd.json', 'w') as f:
json.dump({'data' : [{"name": x} for x in data]},f,sort_keys = True, indent = 4,
ensure_ascii = False)
检查
json.dump({data':[{“name”:x}代表数据中的x],f,sort_keys=True,indent=4,确保_ascii=False)
Yes,我现在已经修复了。检查json.dump({data':[{“name”:x}代表数据中的x),f,sort_keys=True,indent=4,确保_ascii=False)
Yes,我现在已经修复了。