Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Writing to a JSON file
7. Convert a string into a JSON file—practice
Summary

Instruction

Bravo! Of course, we can modify data before we save it in the file. Have a look at our new data, which is in the posts dataset:

posts = [
  {
    "id": 1,
    "body": "This animation has navigated right into my heart.",
    "approved": false
  },
  ...
]

We will choose only those posts that are not approved:

data = []
for post in posts:
  if not post["approved"]:
    data.append(post)

Then we will save the result to a file:

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

Exercise

Choose posts that have fewer than 50 characters, and save the results to a file named short_posts.json.
Note: To get a length of a string, pass it in as an argument to the len() function.

Stuck? Here's a hint!

data = []
for post in posts:
  if len(post["body"]) < 50:
    data.append(post)