How do I write JSON data to a file?

I have JSON data stored in the variable data .

I want to write this to a text file for testing so I don't have to grab the data from the server each time.

Currently, I am trying this:

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

And am receiving the error:

TypeError: must be string or buffer, not dict

How to fix this?


You forgot the actual JSON part - data is a dictionary and not yet JSON-encoded. Write it like this:

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

Note: Works on both 3.x and 2.x .


To get utf8 -encoded file as opposed to ascii -encoded in the accepted answer for Python 2 use:

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

The code is simpler in Python 3:

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

On Windows, the encoding='utf-8' argument to open is still necessary.

To avoid storing an encoded copy of the data in memory (result of dumps ) and to output utf8-encoded bytestrings in both Python 2 and 3, use:

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

The codecs.getwriter call is redundant in Python 3 but required for Python 2


Readability and size:

The use of ensure_acsii=False gives better readability and smaller size:

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

Further improve readability by adding flags indent=4, sort_keys=True (as suggested by dinos66) to arguments of dump or dumps . This way you'll get a nicely indented sorted structure in the json file at the cost of a slightly larger file size.


I would answer with slight modification with aforementioned answers and that is to write a prettified JSON file which human eyes can read better. For this, pass sort_keys as True and indent with 4 space characters and you are good to go. Also take care of ensuring that the ascii codes will not be written in your JSON file:

with open('data.txt', 'w') as outfile:
     json.dump(jsonData, outfile, sort_keys = True, indent = 4,
               ensure_ascii = False)
链接地址: http://www.djcxy.com/p/1332.html

上一篇: 无法测试使用Spring Boot开发的REST API

下一篇: 如何将JSON数据写入文件?