data is a Python dictionary. It needs to be encoded as JSON before writing.

Use this for maximum compatibility (Python 2 and 3):

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

On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:

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

See json documentation.

Answer from phihag on Stack Overflow
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
Python has a built-in package called json, which can be used to work with JSON data. ... If you have a JSON string, you can parse it by using the json.loads() method.
Top answer
1 of 16
3350

data is a Python dictionary. It needs to be encoded as JSON before writing.

Use this for maximum compatibility (Python 2 and 3):

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

On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:

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

See json documentation.

2 of 16
347

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_ascii=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.

Discussions

Convert string to JSON in Python? - Stack Overflow
I'm trying to convert a string, generated from an http request with urllib3. Traceback (most recent call last): File " ", line 1, in data = json.load(data) ... More on stackoverflow.com
🌐 stackoverflow.com
python - How to save a string to a json file - Stack Overflow
I want to save a string to a json file, but when I do it will write it with \" and with quotes at the beginning and at the end. import json name_c = ['Don', 'Perez'] my_details = "data = {" + "... More on stackoverflow.com
🌐 stackoverflow.com
converting JSON to string in Python - Stack Overflow
I did not explain my questions clearly at beginning. Try to use str() and json.dumps() when converting JSON to string in python. More on stackoverflow.com
🌐 stackoverflow.com
how can i convert a string into a json file ?
If it looks like a JSON file it is already a JSON file. There's nothing special about a JSON file except that it's a text file that contains JSON. But the issue is that your file isn't JSON at all, it's an email. More on reddit.com
🌐 r/learnpython
4
3
January 28, 2022
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.4 documentation
February 23, 2026 - fp can now be a binary file. The input encoding should be UTF-8, UTF-16 or UTF-32. Changed in version 3.11: The default parse_int of int() now limits the maximum length of the integer string via the interpreter’s integer string conversion length limitation to help avoid denial of service attacks. json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)¶
🌐
freeCodeCamp
freecodecamp.org › news › python-json-how-to-convert-a-string-to-json
Python JSON – How to Convert a String to JSON
November 9, 2021 - #include json library import json #json string data employee_string = '{"first_name": "Michael", "last_name": "Rodgers", "department": "Marketing"}' #check data type with type() method print(type(employee_string)) #convert string to object json_object = json.loads(employee_string) #check new data type print(type(json_object)) #output #<class 'dict'> You can then access each individual item, like you would when using a Python dictionary:
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-ways-to-convert-string-to-json-object
Convert String to JSON Object - Python - GeeksforGeeks
Let's explore different methods to do this efficiently. json.loads() method is the most commonly used function for parsing a JSON string and converting it into a Python dictionary.
Published   July 11, 2025
🌐
GeeksforGeeks
geeksforgeeks.org › python › reading-and-writing-json-to-a-file-in-python
Reading and Writing JSON to a File in Python - GeeksforGeeks
It takes two parameters: dictionary: ... indentation · After converting the dictionary to a JSON object, simply write it to a file using the "write" function....
Published   August 5, 2025
Find elsewhere
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - Other than that, there are a bunch of optional parameters for json.dump(). The optional parameters of json.dump() are the same as for json.dumps(). You’ll investigate some of them later in this tutorial when you prettify and minify JSON files. In the former sections, you learned how to serialize Python data into JSON-formatted strings and JSON files.
🌐
LearnPython.com
learnpython.com › blog › json-in-python
How to Convert a String to JSON in Python | LearnPython.com
JSON files are often used for ... can learn more about object serialization in this article. The dumps() method converts a Python object to a JSON formatted string....
🌐
Vertabelo Academy
academy.vertabelo.com › course › python-json › writing-json-files › writing-to-json-file › convert-a-string-into-a-json-file
How to Read and Write JSON Files in Python | Learn Python | Vertabelo Academy
No problem – we simply use the json.dump() function. (Note: That's dump without an "s".) This function writes the data converted to its JSON representation into a file. Have a look: with open('data.json', 'w') as outfile: json.dump(data, outfile) ...
Top answer
1 of 2
201

json.dumps() is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.

For instance, if one of the values is None, the str() would produce an invalid JSON which cannot be loaded:

>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

But the dumps() would convert None into null making a valid JSON string that can be loaded:

>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}
2 of 2
2

There are other differences. For instance, {'time': datetime.now()} cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).

🌐
iProyal
iproyal.com › blog › python-string-to-json
How to Convert a Python String to JSON (Beginner’s Guide)
August 18, 2025 - JSON object structures are ideal ... To convert a Python object like a Python dictionary into a JSON string, you need to use the json.dumps() method from Python’s JSON module....
🌐
Reddit
reddit.com › r/learnpython › how can i convert a string into a json file ?
r/learnpython on Reddit: how can i convert a string into a json file ?
January 28, 2022 -

i have a bunch of .txt files that are like this. I need to do some analysis on them. I oringally have been using regex and stuff when i noticed that it kinda looks like a json file. So i was wondering if anybody knows how i can go about convert this in a json and looping through all the texts like this.

I looked at this link right here: https://www.w3schools.com/python/python_json.asp but the problem is that, this wont work because they are already hard coding it as a json string. However, how can i go about making this already into its own dictionary already ?

https://imgur.com/a/Tj7tm01 <-- sorry for the picture, but paste will be so big, that i wont know what to do.

🌐
Programiz
programiz.com › python-programming › json
Python JSON: Read, Write, Parse JSON (With Examples)
If you do not know how to read and write files in Python, we recommend you to check Python File I/O. You can convert a dictionary to JSON string using json.dumps() method.
🌐
W3Schools
w3schools.com › python › gloss_python_convert_into_JSON.asp
Python Convert From Python to JSON
Remove List Duplicates Reverse ... ... If you have a Python object, you can convert it into a JSON string by using the json.dumps() method....
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › python json – how to convert a string to json
Python JSON – How to Convert a String to JSON: Guide & Examples
November 18, 2024 - The json module in Python provides json.dumps() to encode a Python object (usually a dictionary) into a JSON string, and json.loads() to decode a JSON string back into a Python object.
🌐
Analytics Vidhya
analyticsvidhya.com › home › ways to convert string to json object
Ways to Convert String to JSON Object
March 21, 2024 - Discover efficient methods for converting strings to JSON objects in Python. Optimize data handling in your applications!
🌐
Scaler
scaler.com › home › topics › string to json python
Convert String to JSON in Python - Scaler Topics
December 4, 2023 - This function accepts a Python object and produces a JSON string as its output. Decoding (deserializing) JSON: To change a JSON string into a Python object, the json.loads() function is used.