-1

can anybody pls tell me what way I need to use to fetch the last line from JSON file which contains tuples?

lst = (('7', '♠'), ('7', '♣')) # this line is generated each time and has new values

For instance, "deals.json" file contains such lines:

[["7", "\u2660"], ["7", "\u2663"]]
[["8", "\u2660"], ["8", "\u2663"]]

Code:

# here I add new line into the file
with open('deals.json', 'a') as f:
    json.dump(lst,f)
    f.write('\n')

# here I want to read the last line and handle it
with open('deals.json') as f:
    json_data = json.load(f)
    print(json_data)

After running this code it works fine but after the 2nd one it failed while trying to read the file and it's obvious:

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 549)

I know how to do that using text file but have no idea how to read the last line in JSON which contains tuples.

martineau
  • 119,623
  • 25
  • 170
  • 301
Vladimir
  • 62
  • 1
  • 7
  • Does this answer your question? [Loading and parsing a JSON file with multiple JSON objects](https://stackoverflow.com/questions/12451431/loading-and-parsing-a-json-file-with-multiple-json-objects) – rchome Dec 17 '21 at 11:31
  • @rchome partly. but I need to get only the last line w/o reading the whole file line by line because there are a lot lines in it. trying to find the say how to do it.... I will post the result a later – Vladimir Dec 17 '21 at 11:43
  • tuples are not valid json types, so your question is very confusing. could you be more precise? – diggusbickus Dec 17 '21 at 12:21
  • @diggusbickus seems the question is quite clear. I need get only the last line from the JSON file. What exactly I need to note? I use such approach instead of TXT because it'd be easier to handle it but if it's impossible so I think it should be resolved using another way – Vladimir Dec 17 '21 at 12:39
  • @diggusbickus I used such solution https://stackoverflow.com/questions/64082441/save-a-list-of-tuples-to-a-file-and-read-it-again-as-a-list but I do not need to parse / read the whole JSON file – Vladimir Dec 17 '21 at 12:47

1 Answers1

1

Reading just the last line can be achieved like this. Internally the entire file will be read but you don't need to handle that explicitly. If the file was very large then you might need another approach.

import json
with open('deals.json') as f:
    j = json.loads(f.readlines()[-1])
    print(j)

Output:

[['8', '♠'], ['8', '♣']]
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
  • yep, that works fine. thx a lot for assistance. But I think it'd be better to use another approach like you suggested but anyway this works great for another task which I worked on – Vladimir Dec 17 '21 at 13:04