首页 文章

如何将JSON数据写入文件?

提问于
浏览
788

我将JSON数据存储在变量 data 中 .

我想将其写入文本文件进行测试,因此我不必每次都从服务器中获取数据 .

目前,我正在尝试这个:

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

我收到错误:

TypeError: must be string or buffer, not dict

如何解决这个问题?

12 回答

  • 4

    可以按如下方式将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)
    
  • 89

    使用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启动时(否则所有都将在一行),

    • sort_keys :对词典的键进行排序 . 如果要将json文件与diff工具进行比较/将它们置于版本控制之下,这非常有用 .

    • 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

    替代品

    对于您的应用程序,以下可能很重要:

    • 其他编程语言的支持

    • 读/写性能

    • 紧凑度(文件大小)

    另见:Comparison of data serialization formats

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

  • 1494

    要获得 utf8 -encoded文件,而不是在接受的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上, openencoding='utf-8' 参数仍然是必需的 .

    为了避免在内存中存储数据的编码副本( 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需要


    Readability and size:

    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
    

    通过将 indent=4, sort_keys=True (由dinos66建议)添加到 dumpdumps 的参数,进一步提高可读性 . 这样你就可以在json文件中获得一个很好的缩进排序结构,代价是文件大小稍大 .

  • 223

    以前的所有答案都是正确的,这是一个非常简单的例子

    #! /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()
    
  • 19

    你忘了实际的JSON部分 - data 是一个字典,还没有JSON编码 . 写这样:

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

    注意:适用于3.x和2.x.

  • 143

    我会用前面提到的答案稍作修改来回答,那就是编写一个美化的JSON文件,人眼可以更好地阅读 . 为此,将 sort_keys 作为 Trueindent 传递4个空格字符,你就可以了 . 还要注意确保不会在您的JSON文件中写入ascii代码:

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

    如果您尝试使用json格式将pandas数据帧写入文件,我建议这样做

    destination='filepath'
    saveFile = open(destination, 'w')
    saveFile.write(df.to_json())
    saveFile.close()
    
  • 7

    我没有足够的声誉来添加评论,所以我只是在这里写下我讨厌的TypeError的一些发现:

    基本上,我认为这只是Python 2 中的 json.dump() 函数中的一个错误 - 它无法转储包含非ASCII字符的Python(字典/列表)数据,即使您使用 encoding = 'utf-8' 参数打开该文件也是如此 . (即无论你做什么) . 但是, json.dumps() 适用于Python 2和3 .

    为了说明这一点,请跟进phihag的答案:如果 data 包含非ASCII字符,则他的答案中的代码会在Python 2中出现异常 TypeError: must be unicode, not str . (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中运行良好 .

  • 0

    对于那些试图抛弃希腊语或其他“异国情调”语言的人,例如我,但也有问题(unicode错误)与奇怪的字符,如和平符号(\ u262E)或其他通常包含在json格式数据中比如Twitter,解决方案可能如下(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))
    
  • 2
    json.dump(data, open('data.txt', 'wb'))
    
  • 0

    接受的答案很好 . 但是,我使用它遇到了“不是json serializable”错误 .

    这里's how I fixed it with open( 202896 , ' w')作为输出:
    output.write(STR(响应))

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

  • 0

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

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

    列表中的此示例存储到文件中 .

相关问题