Kwinten
Kwinten

Reputation: 71

How to separate key-values per row from a JSON formatted list?

I've been trying to get a more readable output from a JSON list. I have not yet been successful. I hard-coded some data to see if I can get it as I want. This is what I did:

import json

jsonData = {
    "person": {"FirstName": "Kwin", "LastName": "Harley", "Age": 25},
    "DoB": {"DateOfBirth": "19/12/1996", "Birthplace": "Belgium"},
    "insurer":{"id":"12345","contractNumber":"98765432",
               "valid_from":"2020-10-01T00:00:00.000Z","valid_until":"2021-01-30T00:00:00.000Z",
               "representativeID":"135792468",
               "representativeEmail":"[email protected]"}

}
jsonString = json.dumps(jsonData, sort_keys=False, indent=4)

print(jsonString)

Output 1

As you can see, the data is structured nicely.

Now, when I use my main code, the output looks like this:

Output 2

enter image description here

It just returns the data in 1 row :(

Is there a way to fix that? This is the code I have for that:

qrType = qr.type
qrData = json.dumps(qr.data.decode('utf-8'),sort_keys=True)


# print the QR type and data to the terminal
print("[INFORMATION] Found {} barcode:\n{}".format(qrType, qrData))

Upvotes: 1

Views: 205

Answers (1)

2e0byo
2e0byo

Reputation: 5954

I don't think you're passing a dict to json.dumps() at all. qr.data is clearly a string, as you .decode() it. Presumably it's a json string, so you want to do something like this:

formatted_data = json.dumps(json.load(qr.data.decode()), indent=2)
print(formatted_data)

Upvotes: 1

Related Questions