Python json.load 返回字符串而不是字典

标签 python json

我正在接收一个 json 文件,并且只将必要的键及其值复制到一个新的 json 文件中。关于我将值复制到 myDict 的位置,我收到错误“TypeError:字符串索引必须是整数”。据我所知,json.load 返回的是一个字符串而不是字典。我验证了 json 文件并且它具有有效的 json 格式。我正在使用 Python 2.7.12。我到处搜索,但没有找到能解决我的具体问题的答案。非常感谢您能给我的任何帮助。

import os
import sys
import json

def stripSpec(inp, outp):
    #Load json file as python dictionary
    obj  = json.load(open(inp, "r"))

    result=[]

    #Go through JSON and save necessary keys and values
    for i in obj:
        myDict = {}
        myDict["id"]=i.get('id').get('value')
        myDict["data"]["BaselineExposure"]=i.get('data').get('BaselineExposure').get('value')
        myDict["data"]["ColorMatrix2"]=i.get('data').get('ColorMatrix2').get('value')
        result.append(myDict)

    # Output the updated file with pretty JSON
    open(outp, "w").write(json.dumps(result, sort_keys=True, indent=4, ensure_ascii=False, separators=(',', ':')))
    return

#Save input and output paths as variables
inp = sys.argv[1]
outp = sys.argv[2]

#Call function
stripSpec(inp, outp)

这里有一个 json 的例子。它已大大减少,但基本上每个相机型号都有更多条目

[
{ "id": "Canon EOS 100D",
 "data":[{
  "SourceFile": "./Canon 100D/canon_eos_100d_11.dng",
  "ExifToolVersion": 10.07,
  "Directory": "./Canon 100D",
  "FileSize": "18 MB",
  "FileModifyDate": "2016:05:02 23:03:14-07:00",
  "FileAccessDate": "2016:05:03 01:45:03-07:00",
  "FileInodeChangeDate": "2016:05:02 23:03:14-07:00",
  "FilePermissions": "rw-r--r--",
  "ColorMatrix2": "0.6602 -0.0841 -0.0939 -0.4472 1.2458 0.2247 -0.0975 0.2039 0.6148",
  "CameraCalibration1": "1.0648 0 0 0 1 0 0 0 0.9881",
  "CameraCalibration2": "1.0648 0 0 0 1 0 0 0 0.9881",
  "AnalogBalance": "1 1 1",
  "AsShotNeutral": "0.512769 1 0.584809",
  "BaselineExposure": -0.25,
  "RedBalance": 1.950195
  }]
},

最佳答案

在你的 json stub "data" 键中包含列表。在您的代码中,您将其称为字典:i.get('data').get('BaselineExposure')

相反,您应该遍历您的“数据”。 例如:

data = i.get('data')
for d in data:
    print(d.get('BaselineExposure'))

所以基本上要小心嵌套项目。

另外为什么要使用 i.get('id').get('value')。相反,i.get('id') 应该足够了,附加的 .get('value') 应该引发 AttributeError,不是吗?

关于Python json.load 返回字符串而不是字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38361224/

相关文章:

python - "Ambiguous Class Definition"类名 "I"(Python 中的 Pep8)

java - JsonMappingException 重复属性... [简单类型,类 java.lang.Exception]

c++ - 在 qt 中解析嵌套 json 的意外结果(数组不存在)

Python解析从mysql导出的csv

jQuery AJAX 如何使用对象数组?

json - JSON 或 XML 形式的 Powershell 系统信息

java - Jackson 解析包含对象数组和带有动态键的映射数组的 JSON

python - 获取waf将解决方案输出到另一个目录

Python 有序列表搜索与对象列表搜索集

python - 或者条件 Python