我如何将JSON数据写入文件?

我有JSON数据存储在变量data中。

我想把它写到一个文本文件中进行测试,这样我就不必每次都从服务器上抓取数据。

目前,我正在尝试这样做。

obj = open('data.txt', 'wb')
obj.write(data)
obj.close

并收到了错误。

TypeError: must be string or buffer, not dict`.

如何解决这个问题?

解决办法

你忘记了实际的JSON部分--data是一个字典,还没有进行JSON编码。像这样写它以获得最大的兼容性 (Python 2 和 3)。

import json
with open('data.json', 'w') as f:
    json.dump(data, f)

在现代系统中(即Python 3和UTF-8支持),你可以写一个更好的文件,用

import json
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)
评论(21)

要获得utf8编码的文件,而不是Python 2的公认答案中的ascii编码的,请使用。

import io, json
with io.open('data.txt', 'w', encoding='utf-8') as f:
  f.write(json.dumps(data, ensure_ascii=False))

在Python 3中,该代码更简单。

import json
with open('data.txt', 'w') as f:
  json.dump(data, f, ensure_ascii=False)

在Windows上,encoding='utf-8'参数给open仍是必要的。

为了避免在内存中存储数据的编码副本(`dumps'的结果),并在Python 2和3中输出utf8编码的字节符,使用:

import json, codecs
with open('data.txt', 'wb') as f:
    json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)

codecs.getwriter调用在Python 3中是多余的,但在Python 2中是必需的


可读性和大小:

使用ensure_ascii=False会有更好的可读性和更小的尺寸。

>>> json.dumps({'price': '€10'})
'{"price": "\\u20ac10"}'
>>> json.dumps({'price': '€10'}, ensure_ascii=False)
'{"price": "€10"}'

>>> len(json.dumps({'абвгд': 1}))
37
>>> len(json.dumps({'абвгд': 1}, ensure_ascii=False).encode('utf8'))
17

通过在dumpdumps的参数中添加标志indent=4, sort_keys=True(如dinos66所建议)来进一步提高可读性。这样你会在json文件中得到一个很好的缩进排序的结构,代价是文件大小稍大。

评论(18)

我的回答与上述答案略有不同,那就是写一个经过美化的JSON文件,让人眼能更好地阅读。为此,将sort_keys设为Trueindent设为4个空格,就可以了。还要注意确保ascii代码不会被写入你的JSON文件中。

with open('data.txt', 'w') as outfile:
     json.dump(jsonData, outfile, sort_keys = True, indent = 4,
               ensure_ascii = False)
评论(5)

用Python 2+3读取和写入JSON文件。

适用于unicode

# -*- coding: utf-8 -*-
import json

# Make it work for Python 2+3 and with Unicode
import io
try:
    to_unicode = unicode
except NameError:
    to_unicode = str

# Define data
data = {'a list': [1, 42, 3.141, 1337, 'help', u'€'],
        'a string': 'bla',
        'another dict': {'foo': 'bar',
                         'key': 'value',
                         'the answer': 42}}

# Write JSON file
with io.open('data.json', 'w', encoding='utf8') as outfile:
    str_ = json.dumps(data,
                      indent=4, sort_keys=True,
                      separators=(',', ': '), ensure_ascii=False)
    outfile.write(to_unicode(str_))

# Read JSON file
with open('data.json') as data_file:
    data_loaded = json.load(data_file)

print(data == data_loaded)

json.dump的参数说明。

  • indent。 使用4个空格来缩进每个条目,例如:当一个新的dict开始时(否则所有的dict都会在一行中),使用4个空格来缩进。 当一个新的dict开始时,使用4个空格来缩进每个条目(否则所有的条目都会在一行中)。
  • sort_keys。 对字典的键进行排序。 如果你想用差分工具比较json文件/将它们置于版本控制之下,这很有用。
  • separators。 防止Python添加尾部的空白字符。

##有一个包

请看我的实用程序包mpu,超级简单易记。

import mpu.io
data = mpu.io.read('example.json')
mpu.io.write('example.json', data)

创建JSON文件

{
    "a list":[
        1,
        42,
        3.141,
        1337,
        "help",
        "€"
    ],
    "a string":"bla",
    "another dict":{
        "foo":"bar",
        "key":"value",
        "the answer":42
    }
}

常见的文件结尾

.json

替代品

对于您的应用,以下内容可能很重要。

  • 其他编程语言的支持
  • 阅读/写作表现
  • 紧凑性(文件大小)

另见。 数据序列化格式比较

如果你正在寻找一种制作配置文件的方法,你可能会想阅读我的短文Python中的配置文件

评论(3)

对于那些试图转储希腊语或其他"异国情调" 语言,如我,但也遇到了一些问题(unicode错误),如和平符号(\u262E)或其他经常包含在json格式化数据(如Twitter's)中的奇怪字符,解决方案可以如下(sort_keys显然是可选的)。

import codecs, json
with codecs.open('data.json', 'w', 'utf8') as f:
     f.write(json.dumps(data, sort_keys = True, ensure_ascii=False))
评论(1)

我没有足够的声誉来添加评论,所以我只是在这里写一些我对这个恼人的TypeError的发现。

基本上,我认为这是Python中json.dump()函数中的一个bug,只有在Python中2--它不能转储包含非ASCII字符的Python(字典/列表)数据,即使你用encoding = 'utf-8'参数打开文件。 (即 不管你怎么做)。) 但是,json.dumps()在Python 2和3上都能工作。

为了说明这一点,跟进 phihag'的回答。 他的答案中的代码在 Python 2 中出现了异常TypeError: must be unicode, not str, if data contains nonASCII characters. (Python 2.7.6, Debian)。

import json
data = {u'\u0430\u0431\u0432\u0433\u0434': 1} #{u'абвгд': 1}
with open('data.txt', 'w') as outfile:
    json.dump(data, outfile)

然而,它在Python 3中工作得很好。

评论(4)

使用json.dump()json.dumps()在文件中写入数据。 这样写就可以将数据存储在文件中。

import json
data = [1,2,3,4,5]
with open('no.txt', 'w') as txtfile:
    json.dump(data, txtfile)

这个例子在列表中被存储到一个文件。

评论(2)
json.dump(data, open('data.txt', 'wb'))
评论(1)

要写出带缩进的JSON,"pretty print"。

import json

outfile = open('data.json')
json.dump(data, outfile, indent=4)

另外,如果你需要调试格式不正确的JSON,并且想要一个有用的错误信息,请使用import simplejson库,而不是import json(功能应该是一样的)。

评论(0)

如果你想把pandas的数据框写成一个使用json格式的文件,我推荐这样做

destination='filepath'
saveFile = open(destination, 'w')
saveFile.write(df.to_json())
saveFile.close()
评论(0)

之前的答案都是正确的这里举个很简单的例子。

#! /usr/bin/env python
import json

def write_json():
    # create a dictionary  
    student_data = {"students":[]}
    #create a list
    data_holder = student_data["students"]
    # just a counter
    counter = 0
    #loop through if you have multiple items..         
    while counter < 3:
        data_holder.append({'id':counter})
        data_holder.append({'room':counter})
        counter += 1    
    #write the file        
    file_path='/tmp/student_data.json'
    with open(file_path, 'w') as outfile:
        print("writing file to: ",file_path)
        # HERE IS WHERE THE MAGIC HAPPENS 
        json.dump(student_data, outfile)
    outfile.close()     
    print("done")

write_json()

[![在此输入图像描述][1]][1]

[1]: https://i.stack.imgur.com/1CNhG.png

评论(0)

接受的答案是好的。 但是,我在使用该方法时遇到了"is not json serializable" 错误。

我是这样解决的 用open("file-name.json", &#39;w&#39;)作为输出。

output.write(str(response))

虽然它不是一个很好的修复方法,因为它创建的json文件不会有双引号,但是如果你正在寻找快速和肮脏的方法,它是伟大的。

评论(0)

JSON数据可以被写入一个文件,如下所示

hist1 = [{'val_loss': [0.5139984398465246],
'val_acc': [0.8002029867684085],
'loss': [0.593220705309384],
'acc': [0.7687131817929321]},
{'val_loss': [0.46456472964199463],
'val_acc': [0.8173602046780344],
'loss': [0.4932038113037539],
'acc': [0.8063946213802453]}]

写入一个文件。

with open('text1.json', 'w') as f:
     json.dump(hist1, f)
评论(0)