使用以下python代码:
BaseType : System.Object
UnderlyingSystemType : System.Text.RegularExpressions.Regex
FullName : System.Text.RegularExpressions.Regex
我在文件 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)
中得到以下json输出:
asd.json
但是我希望{
"data": {
"name": [
"got01.jpg",
"got02.jpg"
]
}
}
中的json输出为:
asd.json
您能建议一种更好的方法来获得所需结构的输出吗?
答案 0 :(得分:2)
尝试
json.dump({'data' : [{"name": x} for x in data]},f,sort_keys = True, indent = 4, ensure_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)