174k views
5 votes
Convert 'classic_books.json' to Django 'fixture' file format

Read JSON file 'classic_books.json' using Python (There are 4 keys: rank, title, author, year)
JSON can easily be read or writen in Python by using a Dictionary object in Python (read into/write from)
To read a JSON file into a Python dictionary, you use the json.load() method
JSON can easily be read or writen in Python by using a Dictionary object in Python (read into/write from)
To read a JSON file into a Python dictionary, you use the json.load() method
1. Read file classic_books.json
2. Use the json.load() function to parse the JSON into a variable named classics_data.
3. Use a FOR-loop to iterate through the contents of classics_data
4. Within the loop, print each entry in classics_data
5. Create an EMPTY list named books_fixture
6. Use a FOR-loop to iterate through the classics_data again, but while doing so reformat the entries correctly for a Django fixture file
- The 'model' value must be 'books.Book'
- The 'pk' value must be a unique integer value starting with value 1 and ending with the value 10
- The 'fields' data should be gotten from the classics_data entries
7. Print out the contents of books_fixture to verify your reformatting
8. Open file book_import_data.json
9. Write the contents of books_fixture to file book_import_data.json as JSON
10. Close file book_import_data.json

User DirtyMind
by
8.5k points

1 Answer

3 votes

Final answer:

To convert 'classic_books.json' to a Django 'fixture' file, one must read the file, create an empty list for Django fixtures, reformat the original data entries to match Django's required fixture structure, and finally write this data to a new JSON file.

Step-by-step explanation:

To convert 'classic_books.json' to the Django 'fixture' file format, you will need to write a Python script that performs several steps. First, the script must read the JSON data using the json.load() method. Then you iteratively print each book's details from the content.

The next step is creating an empty list for Django fixtures and fill it with reformatted book entries.

These entries should conform to the structure required by Django's fixtures, meaning they should contain a 'model' key with the value 'books.Book', a 'pk' for the primary key that needs to be unique, and the 'fields' key with its value set as the book details from the original JSON. Increment the 'pk' value starting from 1 for each book entry as you iterate through them.

Finally, write this list to a new JSON file, 'book_import_data.json', and close the file upon completion.

User Mateusz Wojtczak
by
7.9k points