0

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. enter image description here

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.

1
  • 1
    json.load(j) already loads your json and transforms it to a python dictionary. When you do json.loads() it pretty much means json.load_string (as opposed to loading from file) so it expects a string but receives a dictionary. If you want to first read the file to a string you should use something like textstring=f.read() or smtg like that. Commented Jul 25, 2019 at 10:26

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.