Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python将数据写入json文件_Json_Python 3.x - Fatal编程技术网

使用python将数据写入json文件

使用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

使用以下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({'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,我现在已经修复了。