Programmer's Python Data - JSON
Written by Mike James   
Wednesday, 03 December 2025
Article Index
Programmer's Python Data - JSON
Multiple Records

Multiple Records

One subtle point about JSON is that you cannot include more than one object in a file. This is not a problem in many situations. For example, reading and writing the configuration data of a program can usually be done in a single object. Things get trickier when you want to write something that you regard as a record to the file. If you want to write a JSON encoding of a single record there is no problem. The file will contain the JSON encoding of the record which can be read back as usual. If you want to write multiple records to the JSON file then things are more difficult. Simply writing one record after another will result in a file that isn’t a JSON file. For example, if you write the data in the example above:

with path.open(mode="wt") as f:
    json.dump(data,f)
    json.dump(data,f)

and try to read it back then you will get a JSONDecodeError exception because a JSON file can only contain a single JSON object.

There are at least two general solutions. The first sticks to the rule of one object per JSON file by turning the records into a list/array. For example:

with path.open(mode="wt") as f:
    json.dump([data,data],f)

Now we have a JSON array containing two records. When you read it back what you get is:

[[1, 2, {'name': 'mike', 'id': 42, 'score': 3.145}],
     [1, 2, {'name': 'mike', 'id': 42, 'score': 3.145}]]

and you can access each record as data[i].

This is a good solution, but it only works when you have all of the data ready to write to the file and can process the file in one go. It doesn’t allow you to add records to the end of the file, unless you change the ending of the file to insert the new record into the array. A simpler and more flexible solution is to write a file that has one JSON object per line. For example:

with path.open(mode="wt") as f:
    s=json.dumps(data)
    print(s,file=f)
    s=json.dumps(data)
    print(s,file=f)

Now we are using dumps to create a JSON string and then print to write a line to the file. To decode the JSON we need to read it line-by-line and use loads to convert each line, so:

with path.open(mode="rt") as f:
    for line in f:
        data= json.loads(line)
        print(data)

displays:

[1, 2, {'name': 'mike', 'id': 42, 'score': 3.145}]
[1, 2, {'name': 'mike', 'id': 42, 'score': 3.145}]

You can see that this works perfectly well, but you need to make sure that there are no embedded new line characters within the data being written.

pythondata180

JSON and Dataclasses

It is fairly easy to use the one-record-per-line approach to saving and loading dataclasses using JSON. To save a dataclass to JSON all you need to do is convert it to a dict using the asdict function and write it to a line in the file. To read it back you then convert the dict back to a dataclass by creating a new instance. For example:

import pathlib
import dataclasses
import json
@dataclasses.dataclass
class person:
    name:str=""
    id:int=0
    score:float=0.0
    
me=person("mike",42,3.145)
path=pathlib.Path("myTextFile.json")
with path.open(mode="wt") as f:
    s=json.dumps(dataclasses.asdict(me))
    print(s,file=f)
        
with path.open(mode="rt") as f:
    for line in f:
        data= json.loads(line)
        me1=person(**data)
        print(me1)

Notice that asdict creates a deep copy so this should work for most dataclasses.

In chapter but not in this extract

  • XML
  • Python XML
  • ElementTree 
  • More XML
  • Pickle
  • Advanced Pickling


Summary

  • Text files are simply binary files where the conversion to a string with suitable decoding is automatic.

  • As well as reading a fixed number of characters, you can also use the readline instruction to read in a single line of text.

  • The print instruction can be used with files and has the advantage of performing the conversion to a string automatically.

  • To make text files able to be read in and decoded you need to use a standard format like CSV, JSON or XML.

  • CSV, Comma Separated Values, is simple but it has a number of disadvantages in that converting from a string to the appropriate data type isn’t generally automatic and there are different dialects of CSV.

  • JSON is a good match to Python’s objects. It is easy to use and is cross-platform.

  • XML is more complicated and probably not a good choice if you can avoid it, but it is a widespread standard and very suitable for representing complex data.

  • XML is not well supported if you are looking for standard processing options such as DOM or SAX. The ElementTree module, however, provides good Python-oriented processing of XML.

  • Pickle is Python’s own object serialization format. It uses a binary file but it is very easy to use to save and load any Python class. Pickle is a good choice if the data is being produced and consumed by Python programs.

Programmer's Python
Everything is Data

Is now available as a print book: Amazon

pythondata360Contents

  1. Python – A Lightning Tour
  2. The Basic Data Type – Numbers
       Extract: Bignum
  3. Truthy & Falsey
  4. Dates & Times
       Extract Naive Dates
  5. Sequences, Lists & Tuples
       Extract Sequences 
  6. Strings
       Extract Unicode Strings
  7. Regular Expressions
       Extract Simple Regular Expressions 
  8. The Dictionary
       Extract The Dictionary 
  9. Iterables, Sets & Generators
       Extract  Iterables 
  10. Comprehensions
       Extract  Comprehensions 
  11. Data Structures & Collections
       Extract Stacks, Queues and Deques
      
    Extract Named Tuples and Counters
  12. Bits & Bit Manipulation
       Extract Bits and BigNum 
       Extract Bit Masks
  13. Bytes
       Extract Bytes And Strings
       Extract Byte Manipulation 
  14. Binary Files
       Extract Files and Paths 
  15. Text Files
       Extract Text Files & CSV 
       Extract JSON ***NEW!!!
  16. Creating Custom Data Classes
        Extract A Custom Data Class 
  17. Python and Native Code
        Extract   Native Code
    Appendix I Python in Visual Studio Code
    Appendix II C Programming Using Visual Studio Code

<ASIN:1871962765>

<ASIN:1871962749>

<ASIN:1871962595>

<ASIN:B0CK71TQ17>

<ASIN:187196265X>

Related Articles

Creating The Python UI With Tkinter

Creating The Python UI With Tkinter - The Canvas Widget

The Python Dictionary

Arrays in Python

Advanced Python Arrays - Introducing NumPy

pico book

 

Comments




or email your comment to: comments@i-programmer.info

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

Banner



Last Updated ( Wednesday, 03 December 2025 )