FAQ: Learn Python: Files - Writing a JSON File

This community-built FAQ covers the “Writing a JSON File” exercise from the lesson “Learn Python: Files”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn Python 3

FAQs on the exercise Writing a JSON File

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

How do we append new data into an existing JSON file? Do we simply open the file with “a” mode, and calling the function json.dump()?

2 Likes

In this lesson, data_payload is a dictionary wrapped in [] - a list of a dictionary. Isn’t JSON like an object and uses just {}?

So, we make a JSON file out of a dictionary in a list…what if we wanted to further convert this list to an actual dictionary? I tried

import json
with open('data.json') as data_json:
  data = json.load(data_json)
print(dict(data))

#Expected result: 
>>{'interesting message': 'What is JSON? A web application\'s little pile of secrets.',
   'follow up': 'But enough talk!'}
#Actual result:
>>> {'interesting message': 'follow up'}
2 Likes

I am curious about this as well, if anybody here has some experience with that type of appending?

Hey guys! My question is actually about the next project, the medical data project linked at the bottom. I didn’t know the best forum to post a question, so I backed up to here.

Good Day! I am Laura and am trying to learn data science to make a career change. I do not have previous tech experience other than working through some MDN courses on HTML and javascript, as well as ~15% of the Full-Stack program through codacademy. I am at the Medical Data group project and am really stuck. Right off the bat, I am having trouble understanding how to import my CSV file.
Can someone explain? Thank you! Below is my initial code and the error. Help!

import csv
ages =
sexes =
bmis =
num_children =
smoker_statuses =
regions =
insurance_charges =
def create_list(lst, csv_file, column_name):
with open(“C:\Users\florence\Documents\python-portfolio-project-starter-files\insurance.csv”) as csv_info:
csv_dict = csv.DictReader(csv_info)
for row in csv_dict:
lst.append(row[column_name])
return lst

The error returned:
File “C:\Users\florence\AppData\Local\Temp/ipykernel_16848/3400907934.py”, line 2
with open(“C:\Users\florence\Documents\python-portfolio-project-starter-files\insurance.csv”) as csv_info:
^
SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape

Below is a link to the project I am referring to:
Group Project: U.S. Medical Insurance Costs | Codecademy

In a normal string Python uses the backslash \ as an escape character so it will be interpreted in an unexpected way in your code (if you’re unsure try just using that string to assign to a variable or print and I think you’ll get the same error, I don’t think it’s from the file itself).

You can either use a forward slash / and Python will interpret the path for you, you can escape each backslash with another backslash, e.g. C:\\Users\\name\\ or you can make the string itself a “raw-string” which no longer interprets the backslash as a special escape character. For a raw string put r before the string, e.g. r"raw\string with a \ is OK".

If that hasn’t covered the issue I think #get-help might be the best shout with #project as another option (shorter queries in get-help, general discussion of the project itself in projects). If you’re posting code to the forums have a look at- How do I format code in my posts? as it contains details of how to retain indentation and format the code which makes it much easier to read :slightly_smiling_face:.

thank you for your tips. I think I’m more stuck then I thought because it doesn’t even seem to recognize my having imported csv, as it says this is not defined… I’ll try to find a better forum to ask…

I too am curious why data_payload has both square brackets, and curly braces

data_payload = [
  {'interesting message': 'What is JSON? A web application\'s little pile of secrets.',
   'follow up': 'But enough talk!'}
]

I was trying to access the data inside of data.json file:

data_payload = [
  {'interesting message': 'What is JSON? A web application\'s little pile of secrets.',
   'follow up': 'But enough talk!'}
]

import json

with open('data.json', 'w') as data_json:
  json.dump(data_payload, data_json)

with open('data.json') as data_json:
  data = json.load(data_json)
  print(data['interesting message'])

… but I got a error

Traceback (most recent call last):
  File "script.py", line 13, in <module>
    print(data['interesting message'])
TypeError: list indices must be integers or slices, not str```

Someone have the idea how to access this data?

try
print(data)
or
print(data[0])
I think this json creates a list containing a dictionary (from the json.load() ), just like the data_payload.

with open('data.json') as data_json:
  data = json.load(data_json)
  for entry in data:
    for key, value in entry.items():
      print("{}: {}".format(key, value))
1 Like

I had the same doubt. Then I realized what we ‘dumped’ to the json file was a list (containing a dictionary), that’s why we had to access it with an INT, like @janbazant1107978602 proposed

I want to know that the json.dump() method, can even convert the list to dictionaries also? As in the example it was just defined as a dictionary, but in the exercise, there is a dictionary within a list. Please help me understand.

I too got curious with this question and seeing no response from anyone did a bit more digging myself. Hope this info helps others.

I started out trying to open with append (“a”) mode and dumping more lines after into JSON, but it gave errors. So it doesn’t appear that the append method works.

Some googling seems to reveal that the only way to do this is a three step process:

  1. You load the JSON via json.load into a Python object.
  2. You append as you would normally using Python, depending on the nature of the JSON file you loaded (list? dictionary? string?)
  3. You create a new or overwrite the existing JSON file using json.dump method.

Reference:

If anyone has better solutions to this, I am all ears.

JSON can anything you want to save from Python long term. The lesson just demonstrates two such examples. In the example, they saved a dictionary. In the exercise, they saved a list of dictionary. There is nothing that the method is doingg to convert the list into a dictionary. When you reload the JSON file of list of dictionary, it stays a list of dictionary.