JSON data in python is essentially a dictionary (at least they are interchangeable, there are some minor differences with the formatting). Have you tried saving a dictionary to a simple text file? my_data = { 'a': [1, 2, 3], 'b': {'foo': 'bar', 'baz': [4, 5, 6]} } with open('test_file.txt', 'w') as file: file.write(my_data) This is not possible because Python expects a string that it can write to a file. It doesn't know how to turn a dictionary into something it can write to a file. But, maybe you then do this instead: my_data = { "a": [1, 2, 3], "b": {"foo": "bar", "baz": [4, 5, 6]} } with open('test_file.txt', 'w') as file: # cast my_data to a string first file.write(str(my_data)) And it works. But what if you want to read that file? with open('test_file.txt', 'r') as file: read_data = file.read() Now you have a problem, because your output is this string: "{'a': [1, 2, 3], 'b': {'foo': 'bar', 'baz': [4, 5, 6]}}" How do you convert a string into a dictionary? This here doesn't work: with open('test_file.txt', 'r') as file: read_data = dict(file.read()) Python by itself does not know how to convert a string into a dictionary. For that you need JSON. Also it makes sure that you meet all the conventions of the JSON format so that you can exchange data between different languages (e.g. from Python to JavaScript). The other thing is, if you have a .txt file, how would anybody know that this file contains a data structure without opening the file? If the file extension says "JSON" everybody knows how to interpret the data. Same with .XML, .HTML etc. Answer from MattR0se on reddit.com
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ why json.dump() and .load() are really needed?
r/learnpython on Reddit: Why json.dump() and .load() are really needed?
October 15, 2020 -

Hi, hope everyone is well.

Just nearing the basics end of PCC book, I'm at saving user's data now. What exactly is the reason, when storing simple data, to use json.dump() or load(), instead of just saving and then reading it from simple text file?

I just can't place it in my head why do I really need it and it always makes it more difficult for me to learn if that's the case.

Thank you all in advance.

Top answer
1 of 8
6
JSON data in python is essentially a dictionary (at least they are interchangeable, there are some minor differences with the formatting). Have you tried saving a dictionary to a simple text file? my_data = { 'a': [1, 2, 3], 'b': {'foo': 'bar', 'baz': [4, 5, 6]} } with open('test_file.txt', 'w') as file: file.write(my_data) This is not possible because Python expects a string that it can write to a file. It doesn't know how to turn a dictionary into something it can write to a file. But, maybe you then do this instead: my_data = { "a": [1, 2, 3], "b": {"foo": "bar", "baz": [4, 5, 6]} } with open('test_file.txt', 'w') as file: # cast my_data to a string first file.write(str(my_data)) And it works. But what if you want to read that file? with open('test_file.txt', 'r') as file: read_data = file.read() Now you have a problem, because your output is this string: "{'a': [1, 2, 3], 'b': {'foo': 'bar', 'baz': [4, 5, 6]}}" How do you convert a string into a dictionary? This here doesn't work: with open('test_file.txt', 'r') as file: read_data = dict(file.read()) Python by itself does not know how to convert a string into a dictionary. For that you need JSON. Also it makes sure that you meet all the conventions of the JSON format so that you can exchange data between different languages (e.g. from Python to JavaScript). The other thing is, if you have a .txt file, how would anybody know that this file contains a data structure without opening the file? If the file extension says "JSON" everybody knows how to interpret the data. Same with .XML, .HTML etc.
2 of 8
3
How would you structure the text file so that you can load the data later?
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ write() vs. json.dump()
r/learnpython on Reddit: write() vs. json.dump()
July 15, 2016 - Then the difference is that the second is less typing, and it affords the possibility for better performance since the JSON module can theoretically stream the JSON to the file in chunks, whereas in the first version it has to create the entire ...
๐ŸŒ
Medium
medium.com โ€บ snowflake โ€บ json-methods-load-vs-loads-and-dump-vs-dumps-21434a520b17
JSON Methods: load vs loads() and dump vs dumps() | by Sachin Mittal | Snowflake Builders Blog: Data Engineers, App Developers, AI, & Data Science | Medium
May 2, 2022 - For example, Receive an HTTP request and store it in a Python dictionary or any Python object using json.loads().Send that data back to the requested application (Snowflake) so you need to convert the Python dictionary object into a JSON formatted string to send as a response in JSON string. To do this you need to use json.dumps().
๐ŸŒ
ReqBin
reqbin.com โ€บ code โ€บ python โ€บ c6fxmvxt โ€บ python-dump-vs-dumps-example
What is the difference between json.dump() vs json.dumps() in Python?
The json.dump() method converts a Python object into a JSON and writes it to a file, while the json.dumps() method encodes a Python object into JSON and returns a string. By default, json.dump() and json.dumps() generate minified versions of ...
Find elsewhere
๐ŸŒ
PYnative
pynative.com โ€บ home โ€บ python โ€บ json โ€บ python json dump() and dumps() for json encoding
Python JSON dump() and dumps() for JSON Encoding
May 14, 2021 - Understand various use of json.dump() and dumps(). Encode Python objects into JSON and Write it in a file.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ what-is-the-difference-between-jsonloads-and-jsondumps
What is the difference between json.loads() and json.dumps()?
The json.loads() takes in a string and returns a python object and the json.dumps() takes in a Python object and returns a JSON string.
๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ latest โ€บ you must know python json dumps, but maybe not all aspects
You Must Know Python JSON Dumps, But Maybe Not All Aspects | Towards Data Science
January 20, 2025 - Then, if we check the working directory, the file my.json should be there with the converted JSON string. If we use dumps(), it simply dumps the dictionary into a string.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ to dump or to dumps, that is the question...?
r/learnprogramming on Reddit: To Dump or to Dumps, that is the Question...?
September 22, 2022 -

Hi all,

I have another assignment where I've been asked to write a Python code to dump the JSON data from an API into a database table. The instructors all say to use dumps, however, I keep getting an error about string formatting. I know I am missing something simple.

Here is the assignment:

Load the first 100 Pokemon JSON documents from the PokeAPI and store them in a table:
CREATE TABLE IF NOT EXISTS pokeapi (id INTEGER, body JSONB);
You need to write this code from scratch. All you need to do is loop through and retrieve the JSON data for urls ending in 1..100 and store it in the above table.

That is literally all that the actual assignment provides. The instructor put this pseudocode in the discussion forums because a lot of people were frustrated by the lack of clarity in the assignment.

1 range() loop
2    concatenate count to the url
3    requests.get()
4    json()
5    dumps()
6    sql = INSERT...
7    cur.execute()
8
9 conn.commit()
10 cur.close()

This is what I have come up with so far:

  1 import psycopg2
  2 import hidden
  3 import time
  4 import myutils
  5 import requests
  6 import json
  7 
  8 secrets = hidden.secrets()
  9 
 10 conn = psycopg2.connect(host=secrets['host'],
 11         port=secrets['port'],
 12         database=secrets['database'],
 13         user=secrets['user'],
 14         password=secrets['pass'],
 15         connect_timeout=5)
 16 
 17 cur = conn.cursor()
 18 
 19 sql = 'DROP TABLE IF EXISTS pokeapi CASCADE;'
 20 print(sql)
 21 cur.execute(sql)
 22 
 23 sql = 'CREATE TABLE IF NOT EXISTS pokeapi (id INTEGER, body JSONB);'
 24 print(sql)
 25 cur.execute(sql)
 26 
 27 conn.commit()
 28 
 29 defaulturl = 'https://pokeapi.co/api/v2/pokemon-species/'
 30 
 31 for i in range(1, 100):
 32         url = 'https://pokeapi.co/api/v2/pokemon-species/' + str(i)
 33         print(url)
 34         r = requests.get(url)
 35         j = r.json()
 36         w = json.dumps(j)
 37         sql = 'INSERT INTO pokeapi (id, body) VALUES (%s, w);'                                                                                                                                  
 38         cur.execute(sql, (i, json))
 39         
 40 conn.commit()
 41 cur.close()

When I run it like that I get this error:

DROP TABLE IF EXISTS pokeapi CASCADE;
CREATE TABLE IF NOT EXISTS pokeapi (id INTEGER, body JSONB);
https://pokeapi.co/api/v2/pokemon-species/1
Traceback (most recent call last):
  File "/home/[myname]/pokeapi.py", line 38, in <module>
    cur.execute(sql, (i, json))
TypeError: not all arguments converted during string formatting

I even put a print(w) line between 36 and 37 and it did a whole bunch of JSON so the problem, I'm guessing, is with the INSERT statement or the execution.

I have tried everything that I can think of in the execute statement (i, w), (i, text), (i, json), (int, text), (int, json) and so many other variations.

I am sure that I am missing something obvious to a veteran programmer. This class is literally my first exposure to computer programming and I feel like I've done okay except for the last two assignments.

I appreciate all of your help!
Thank you :)

๐ŸŒ
Vitoshacademy
vitoshacademy.com โ€บ json-dump-vs-json-dumps-in-python
Json.dump vs json.dumps in Python โ€“ Useful code
The difference between json.dump and json.dumps is actually quite visible: ยท Still, I am going to give a few example with these, as the dumps has a few nice built-in features:
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ json.dumps() returning json with extra paratheses on either end.
r/learnpython on Reddit: JSON.dumps() returning JSON with extra paratheses on either end.
February 9, 2023 -

Hi! I'm running a Python Back-End with an Android client in Java. I'm trying to return a JSON response to a request that I'm receiving. I've had previous issues with this, as my request has objects within objects but that was solved using a custom Encoder. Now, when I return my response after using json.dumps(), my Java client, parses it through GSON but it's invalid

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 2 path $

When printing the response out in the console I get:

{"user": {"firstName": "Bob", "lastName": "Miller", "username": "bobbyboi", "profileImage": "image"}, "authToken": {"authToken": "authtoken", "dateTime": "time"}} 

which looks correct, but not for GSON. It ends up coming in as

"{"user": {"firstName": "Bob", "lastName": "Miller", "username": "bobbyboi", "profileImage": "image"}, "authToken": {"authToken": "authtoken", "dateTime": "time"}}" 

with the extra apostrophes at the end.

Here is my python code:

dummyUser = User("Bob", "Miller", "bobbyboi", "image")
dummyAuth = AuthToken("authtoken", "time") 
response = LoginResponse(dummyUser, dummyAuth) 
return json.dumps(response, cls=MyEncoder) 

And the encoder, just in case that's the issue:

class MyEncoder(json.JSONEncoder):     
    def default(self, o):        
        if hasattr(o, "encode"):            
        return o.encode()         
        else:             
        return json.JSONEncoder.default(self,o) 

And then the Java GSON:

if (http.getResponseCode() == HttpURLConnection.HTTP_OK){
   InputStream inputStream = http.getInputStream();            
   String parseRequest = readString(inputStream);                                

System.out.println(parseRequest);LoginResponse response = gson.fromJson(parseRequest, LoginResponse.class)

EDIT: Thanks, guys, for responding! I ended up fixing it by just modifying the string on the Java side to remove the extra paratheses and the backslashes "/" which apparently GSON doesn't like? I've used GSON before with Java backends and never had this issue before. Weird....Thanks for your help though!

๐ŸŒ
Medium
pjcarroll.medium.com โ€บ json-dump-vs-json-dumps-json-load-vs-json-loads-b959f2647c9f
json.dump vs json.dumps, json.load vs json.loads | by PJ Carroll | Medium
December 27, 2020 - There it is: json.dump() sends data straight to a filehandler, json.dumps outputs it as a string.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ json-dump-in-python
json.dump() in Python - GeeksforGeeks
January 8, 2020 - Both json.dump() and json.dumps() are used to convert Python objects into JSON, but they differ in where the JSON output goes a file or a string.
๐ŸŒ
Medium
medium.com โ€บ data-science โ€บ you-must-know-python-json-dumps-but-maybe-not-all-aspects-fa8d98a76aa0
You Must Know Python JSON Dumps, But Maybe Not All Aspects | by Christopher Tao | TDS Archive | Medium
December 6, 2021 - Python has built-in support to JSON documents, by its โ€œjsonโ€ module. I bet most of us have used it, and some of us have used it a lot. We know that we can use the json.dumps() method to easily convert a Python dictionary object into a JSON string.