无法使用Python3解析文件中的JSON。

huangapple go评论61阅读模式
英文:

Unable to parse JSON from file using Python3

问题

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.load(json_vmaf_file)
        vmaf_values.append((crf, vm["pooled_metrics"]["vmaf"]["harmonic_mean"]))

这段代码应该可以正常加载你的JSON文件,并获取所需的值。确保你已经导入了json模块。如果你仍然遇到问题,可能是JSON文件本身有一些不可见的问题,你可以尝试使用其他JSON验证工具来检查文件的有效性。

英文:

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?

答案1

得分: 0

loads是json库的一个方法,如文档所述https://docs.python.org/3/library/json.html#json.loads。在这种情况下,您遇到了一个AttributeError,这意味着您可能已经创建了另一个名为"json"的变量,当您调用json.loads时,它调用了那个变量,因此它不会有一个loads方法。

英文:

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.

huangapple
  • 本文由 发表于 2023年2月10日 07:05:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75405377.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定