简体   繁体   中英

Python Interprter error while loading JSON file using json.load()

This is my python code for parsing a JSON file.

import os
import argparse
import json
import datetime


ResultsJson = "sample.json"
try:
    with open(ResultsJson, 'r') as j:
        jsonbuffer = json.load(j)
        result_data = json.loads(jsonbuffer)
        print("Just after loading json")
except Exception as e:
        print(e, exc_info=True)

I get an error like in the snapshot attached below. 在此处输入图片说明

I'm also attaching the JSON file "sample.json" that I'm using here. sample.json

{
  "idx": 1,
  "timestamp": 1562781093.1182132,
  "machine_id": "tool_2",
  "part_id": "af71ce94-e9b2-47c0-ab47-a82600616b6d",
  "image_id": "14cfb9e9-1f38-4126-821b-284d7584b739",
  "cam_sn": "camera-serial-number",
  "defects": [
    {
      "type": 0,
      "tl": [169, 776],
      "br": [207, 799]
    },
    {
      "type": 0,
      "tl": [404, 224],
      "br": [475, 228]
    },
    {
      "type": 1,
      "tl": [81, 765],
      "br": [130, 782]
    }
  ],
  "display_info": [
    {
      "info": "DEFECT DETECTED",
      "priority": 2
    }
  ]
}

Not sure what I missed here. I'm very new to Python (Coming from C++ background). Please be easy on me if I've missed something basic.

You don't need this line:

result_data = json.loads(jsonbuffer)

...because jsonbuffer is the result of json.load , so it's already the result of parsing the JSON file. In your case it's a Python dictionary, but json.loads expects a string, so you get an error.

Also, as the second error message says, exc_info is not a valid keyword argument of the print function. If you wanted to print the exception, just do print(e) .

You can do either:

with open(ResultsJson, 'r') as j:
    result_data = json.load(j)
    print("Just after loading json")

Or:

with open(ResultsJson, 'r') as j:
    result_data = json.loads(j.read())
    print("Just after loading json")

The json.load() internally calls the json.loads() function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM