0

I am new to Python, and I want to convert a JSON file and print it to the console. When I try to print the whole JSON it is throwing

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

My code:

import json

with open('venv/Vt.json', 'r') as json_file:
    parsed_json = json.load(json_file)
for idd in parsed_json:
    print(idd['t_id'])

My JSON file:

{"index":{"_id":0}}
{"t_id":0,"timestamp":"2016-06-01T09:23:39Z","stat":"571","mod":"M02"}
{"index":{"_id":1}}
{"t_id":0,"timestamp":"2016-06-01T09:23:39Z","stat":"571","mod":"M02"}
moopet
  • 6,014
  • 1
  • 29
  • 36
  • 3
    Your JSON isn't valid. `json.load` expects a single object. You could wrap your code in `[ ... ]` to make it a list (include commas after each object). Or you could loop through the lines in your file and call `json.loads()` on each one. – Cfreak Oct 16 '19 at 17:05
  • Possible duplicate of [multiple Json objects in one file extract by python](https://stackoverflow.com/questions/27907633/multiple-json-objects-in-one-file-extract-by-python) – glibdud Oct 16 '19 at 17:35
  • But I have 1000 of json file of same type. How do I take specific values ? – Mahesh M K S Oct 20 '19 at 15:40

1 Answers1

0

While you wait for a better answer, this code (while not great) solves your issue:

with open('venv/Vt.json', 'r') as json_file:
    try:
        t_ids = [json.loads(line)['t_id'] for line in json_file.readlines()]
        print(t_ids)
    except Exception:
        pass

Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55
Tom
  • 571
  • 2
  • 11
  • 29
  • AttributeError: '_io.TextIOWrapper' object has no attribute 'splitlines' I am getting this error. – Mahesh M K S Oct 20 '19 at 15:39
  • Ah ye my bad, I quickly wrote it down as str code to troubleshoot rather than an open file object. I've fixed it – Tom Oct 20 '19 at 16:13
  • Cool... Thank You. Just I had tried like this, lines = [re.sub("[\[\{\]]*", "", one_object.rstrip()) for one_object in json_as_string.readlines()] json_as_list = "".join(lines).split('}') Both worked but your's was very simple and clean. Thank's for the support – Mahesh M K S Oct 20 '19 at 16:31