Jith
Jith

Reputation: 109

how to convert a text file of JSON to JSON array in Python?

I'm a bit stumped on how to convert a text file of JSON to JSON array in Python?

So I have a text file that is constantly being written to with JSON entries, however the text file does not have bracket to call it as a JSON Array.

{"apple": "2", "orange": "3"}, {"apple": "5", "orange": "6"}, {"apple": "9", "orange": "10"} ...

How can I put that into a JSON array? My end goal is read the latest entry every time there is a new entry added. The JSON file is created by some other program that I have no control over, and its being written to constantly, so I can't just slap brackets to the start and end of the file.

Thanks

Upvotes: 1

Views: 1164

Answers (1)

costaparas
costaparas

Reputation: 5237

After you read in the file, you can treat it as a string, to which you add brackets to. Then, pass that to the json library to decode it as JSON for you.

import json

with open('data.txt') as f:
    raw_data = f.read().splitlines()[-1]
    list_data = f'[{raw_data}]'
    json_data = json.loads(list_data)
    print(json_data)

# [{'apple': '2', 'orange': '3'}, {'apple': '5', 'orange': '6'}, {'apple': '9', 'orange': '10'}]

This assumes that each line of the file should become a new array. The code extracts the last line of the file and converts it.

Upvotes: 1

Related Questions