简体   繁体   English

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

[英]Python json.load returning string instead of dictionary

I'm taking in a json file and only copying the necesary keys and their values to a new json file.我正在接收一个 json 文件,并且只将必要的键和它们的值复制到一个新的 json 文件中。 I'm getting the error "TypeError: string indices must be integers" in reference to where I'm copying the values to myDict.我收到错误“类型错误:字符串索引必须是整数”,参考我将值复制到 myDict 的位置。 From what I gather, json.load is returning a string rather than a dictionary.据我所知, json.load 返回的是字符串而不是字典。 I validated the json file and it has valid json format.我验证了 json 文件,它具有有效的 json 格式。 I'm using Python 2.7.12.我正在使用 Python 2.7.12。 I've searched everywhere and haven't found an answer that answers my specific problem.我到处搜索,但没有找到可以解决我的具体问题的答案。 Any help you can give me is greatly appreciated.非常感谢您能给我的任何帮助。

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)

an example of the json is here. json 的一个例子是here。 It has been drastically reduced but basically there is more entries for each camera model它已大幅减少,但基本上每个相机型号都有更多条目

[
{ "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
  }]
},

In your json stub "data" key contains list.在您的 json 存根中, "data"键包含列表。 In your code you refer to it as a dictionary: i.get('data').get('BaselineExposure')在您的代码中,您将其称为字典: i.get('data').get('BaselineExposure')

Instead you should iterate through your "data" .相反,您应该遍历您的"data" For example:例如:

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

So basically be careful with nested items.所以基本上要小心嵌套项目。

Also why do you use i.get('id').get('value') .还有你为什么使用i.get('id').get('value') Instead i.get('id') should be enough and additional .get('value') should raise AttributeError , isn't it?相反, i.get('id')应该足够了,额外的.get('value')应该引发AttributeError ,不是吗?

Overview: I assume the json is stored as a dictionary.概述:我假设 json 存储为字典。 I convert the dictionary to a json string using json.dumps.我使用 json.dumps 将字典转换为 json 字符串。 I pip install json2xml json2xml to convert the json string so it can be converted to xml.我 pip install json2xml json2xml 来转换 json 字符串,以便它可以转换为 xml。 I then load the xml into a dom tree for searching.然后我将 xml 加载到 dom 树中进行搜索。 I search for the node in the xml tree using getElementsByTagName and display the value.我使用 getElementsByTagName 在 xml 树中搜索节点并显示值。 My approach is more programmer friendly.我的方法对程序员更友好。

from json2xml import json2xml
from json2xml.utils import readfromurl, readfromstring, readfromjson
from xml.dom.minidom import parse, parseString

dict={
  "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
    }]
 }

 #convert dictionary to a string
 json_data=json.dumps(dict,indent=4)
 data=readfromstring(json_data)
 xml=json2xml.Json2xml(data).to_xml()

 dom=parseString(xml)

 element=dom.getElementsByTagName('BaselineExposure') 
 print(element[0].firstChild.nodeValue)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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