Unable to parse JSON from file using Python3

Question:

I’m trying to get the value of ["pooled_metrics"]["vmaf"]["harmonic_mean"] from a JSON file I want to parse using python. This is the current state of my code:

for crf in crf_ranges:
    vmaf_output_crf_list_log = job['config']['output_dir'] + '/' + build_name(stream) + f'/vmaf_{crf}.json'
    # read the vmaf_output_crf_list_log file and get value from ["pooled_metrics"]["vmaf"]["harmonic_mean"]
    with open(vmaf_output_crf_list_log, 'r') as json_vmaf_file:
        # load the json_string["pooled_metrics"] into a python dictionary
        vm = json.loads(json_vmaf_file.read())
        vmaf_values.append((crf, vm["pooled_metrics"]["vmaf"]["harmonic_mean"]))

This will give me back the following error:

AttributeError: ‘dict’ object has no attribute ‘loads’

I always get back the same AttributeError not matter if I use "load" or "loads".

I validated the contents of the JSON, which is valid using various online validators, but still, I am not able to load the JSON for further parsing operations.

I expect that I can load a file that contains valid JSON data. The content of the file looks like this:

{
  "frames": [
    {
      "frameNum": 0,
      "metrics": {
        "integer_vif_scale2": 0.997330,
      }
    },
  ],
  "pooled_metrics": {
    "vmaf": {
      "min": 89.617207,
      "harmonic_mean": 99.868023
    }
  },
  "aggregate_metrics": {
  }
}

Can somebody provide me some advice onto this behavior, what does it seem so absolutely impossible to load this JSON file?

Asked By: Martin Hammer

||

Answers:

loads is a method for the json library as the docs say https://docs.python.org/3/library/json.html#json.loads. In this case you are having a AttributeError this means that probably you have created another variable named "json" and when you call json.loads is calling that variable hence it won’t have a loads method.

Answered By: Sergio2405
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.