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}
Answer from alecxe on Stack Overflow
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).

🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
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
Convert from string to json python.
title: something funny This isn't JSON, but it might be YAML. You'll have to be clearer about what you're trying to do and what you've tried. Does anyone have an idea on how should I approach this? The point of Python's JSON library is that you don't work with JSON. You work with dictionaries, lists, and strings and then either convert into JSON (for transmission across some kind of socket, usually) or from JSON (when you're receiving it from something else, like an API.) but with no luck You really have to make an effort to be clearer. We're not sitting there looking over your shoulder; we don't know anything about the problem that you don't tell us. More on reddit.com
🌐 r/learnpython
8
1
May 5, 2019
Text still behaves as a string after converting it to json?
What does the returned JSON look like? If you print(r.text) immediately after fetching it. Also the requests lib has a response.json() function which would save the conversion. More on reddit.com
🌐 r/learnpython
7
7
February 10, 2024
Writing a json object as a string
How is writing the string yourself any different than writing it using the json module with .dumps? Do you mean that you get an error if you use json.dump (no 's')? json.dumps writes a string - docs json.dump writes to a file (or IO object) - docs But to answer your question, yes, JSON data is just plain text. You can write your own and the json.load will work just fine. More on reddit.com
🌐 r/learnpython
8
3
December 1, 2014
People also ask

How to Read and Parse JSON files in Python
To parse a JSON file in Python, we can use the same json module we used in the previous section. The only difference is that instead of passing a JSON string to json.loads(), we pass the contents of a JSON file.
🌐
blog.apify.com
blog.apify.com › how-to-parse-json-with-python
How to parse JSON with Python
How to parse JSON with Python Pandas
To parse JSON with Python Pandas, we can use the pandas.read_json() function. This function can read JSON data into a pandas DataFrame, which allows for easy manipulation and analysis of the data.
🌐
blog.apify.com
blog.apify.com › how-to-parse-json-with-python
How to parse JSON with Python
How to Pretty Print JSON data in Python
When working with JSON data in Python, it can often be helpful to pretty print the data, which means to format it in a more human-readable way. The json module provides a method called json.dumps() that can be used to pretty print JSON data.
🌐
blog.apify.com
blog.apify.com › how-to-parse-json-with-python
How to parse JSON with Python
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-convert-json-to-string
Convert JSON to string - Python - GeeksforGeeks
July 12, 2025 - This code creates a Python dictionary and converts it into a JSON string using json.dumps(). The result is printed along with its type, confirming that the output is now a string. ... import json # create a sample json a = {"name" : "GeeksforGeeks", "Topic" : "Json to String", "Method": 1} y = json.dumps(a) print(y) print(type(y))
🌐
Python
docs.python.org › 3 › library › json.html
json — JSON encoder and decoder
Decode a JSON document from s (a str beginning with a JSON document) and return a 2-tuple of the Python representation and the index in s where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end.
🌐
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:
Find elsewhere
🌐
Apify
blog.apify.com › how-to-parse-json-with-python
How to parse JSON with Python
March 11, 2025 - Learn to parse JSON strings with Python's built-in json module and convert JSON files using pandas.
🌐
iProyal
iproyal.com › blog › python-string-to-json
How to Convert a Python String to JSON (Beginner’s Guide)
August 18, 2025 - Use `json.loads()` from the JSON module to convert a JSON string into a Python object (like a Python dictionary).
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › convert json object to string in python
Convert JSON Object to String in Python - Spark By {Examples}
May 21, 2024 - We are often required to convert JSON objects to a String in Python, you could do this in multiple ways, for example, json.dumps() is utilized to convert
🌐
GitHub
github.com › luminati-io › Parse-json-in-python
GitHub - luminati-io/Parse-json-in-python: Learn to convert JSON to Python dictionaries and objects, use API responses, handle files, and explore limitations. · GitHub
The built-in Python json library exposes a complete API to deal with JSON. In particular, it has two key functions: loads and load. The loads function is for parsing JSON data from a string, while the load function is for parsing JSON data into bytes.
Author: luminati-io
🌐
Zyte
zyte.com › home › blog › json parsing with python [practical guide]
JSON Parsing with Python [Practical Guide]
December 3, 2024 - Working with JSON in Python also involves modifying the data by adding, updating or deleting elements. In this post we will focus on the basics, so we will be using the json built-in package, as it provides all basic functions we require to accomplish these tasks. To add an element, you can modify the corresponding mapping in the JSON object using standard dictionary syntax. For example: ... 1import json 2 3json_string = '{"model": "Model X", "year": 2022}' 4json_data = json.loads(json_string) 5json_data['color'] = 'red' 6 7print(json_data) # Output: {'model': 'Model X', 'year': 2022, 'color': 'red'}
🌐
YouTube
youtube.com › automate with rakesh
Python Pretty Print JSON String: Enhance Readability with Proper Formatting of JSON - YouTube
Learn the art of enhancing your JSON data's readability using Python's pretty print technique. In this tutorial, discover how to transform complex JSON strin...
Published: August 19, 2023
Views: 2K
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - As a Python developer, you may need to pay extra attention to the Boolean values. Instead of using True or False in title case, you must use the lowercase JavaScript-style Booleans true or false. Unfortunately, there are some other details in the JSON syntax that you may stumble over as a developer. You’ll have a look at them next. The JSON standard doesn’t allow any comments, trailing commas, or single quotes for strings.
🌐
Reddit
reddit.com › r/learnpython › convert from string to json python.
r/learnpython on Reddit: Convert from string to json python.
May 5, 2019 -

Hello,

UPDATE:

The problem is that I need to change the convert the data from string type to JSON.

How I got to the respective string ?

I am writing out the data from a dict. (no, I cannot convert from dict to JSON due to the architecture of the code behind)

The dictionary has the following values in it:

('sid', 'something funny'), ('subtitle', 'Nothing yet'), ('date', 'Today'), ('weather': 'Hot')

Afterwards I do the following: (The data is required as a string)

for key in dicts:

data = data + key + ' : ' + result[key] + '\n'

Then I have to change from this

title: something funny

subtitle: Nothing yet

date: Today

weather: Hot

to this

{

'title': 'something funny',

'subtitle': 'Nothing yet',

'date': 'Today',

'weather': 'Hot',

}

So far I've tried some variation of the following (but with no luck):

json.dumps(data, separators=('\n', ': '), sort_keys=True)

Does anyone have an idea on how should I approach this?

Thanks in advance!

🌐
Reddit
reddit.com › r/learnpython › text still behaves as a string after converting it to json?
r/learnpython on Reddit: Text still behaves as a string after converting it to json?
February 10, 2024 -

I'm making a get request to a website and it returns me a string that is written as json (essentially taking json and converting it to a string). I then convert that string into json but it seems it still behaves as a string when I try to change one of the values. It gives me this error: "TypeError: 'str' object does not support item assignment". Why?

Here is my code:

r = requests.get(link) # get request

data = json.loads(r.text) # turn response into json

data["body"]["snip"]["balance"] = int(new_balance) # go through the json and replace the value named "balance" and thats where it throws the error.

Also, the "balance" value is an integer by default so I'm not changing its type.

🌐
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
🌐
Reddit
reddit.com › r/learnpython › writing a json object as a string
r/learnpython on Reddit: Writing a json object as a string
December 1, 2014 -

I have a script that dumps a json object into a .json file after execution. Normally I would use json.dumps(dictionary) to do this. However I have a cache memory restriction that throws a monkey wrench into my plans. If the dictionary gets too big, I run into problems. I was wondering if I could write a dictionary as a string and them open it back up as a json file. For example, would thing like this be a good idea?

with open('test.json', 'wb') as fw:
    fw.write('{"a":"b"}')

Of course, this is a very trivial example that i came up with. If anyone has a better idea pls show me

🌐
GitHub
gist.github.com › craigsdennis › 0f00869fe2e2f2da9d6287984c62b2af
Convert Python String to JSON · GitHub
Convert Python String to JSON. GitHub Gist: instantly share code, notes, and snippets.