从外部函数检索的Json对象的输出特定值

时间:2014-03-11 13:49:35

标签: python json exiftool

在执行

时,我无法获得正确的输出值
print metadata["File:FileSize"]

它给了我list indices must be a integer, not str错误。 我以为json.loads会返回一个字典。

变量metadata像这样从类中的exiftool中检索出来:

def get_metadata(self, *filenames):
    return json.loads(self.execute("-G", "-j", "-n", *filenames))

在主程序流程中我这样做:

metadata = exif.get_metadata(fileName)
print metadata
print metadata["File:FileSize"]

有人可以帮我弄清楚我做错了什么吗?

以下是原始exiftool查询的示例:

[{
  "SourceFile": "/media/mango/MF-HDD-277/01_audio/Computer Arts royalty-free audio samples/Disc 191 - soundsnap/ComputerArtsDisc191_SoundSnapSamples_088_Bend03.wav",
  "ExifTool:ExifToolVersion": 9.13,
  "File:FileName": "ComputerArtsDisc191_SoundSnapSamples_088_Bend03.wav",
  "File:Directory": "/media/mango/MF-HDD-277/01_audio/Computer Arts royalty-free audio samples/Disc 191 - soundsnap",
  "File:FileSize": 146948,
  "File:FileModifyDate": "2010:10:24 11:17:20-04:00",
  "File:FileAccessDate": "2014:01:29 15:58:48-05:00",
  "File:FileInodeChangeDate": "2014:01:21 13:28:00-05:00",
  "File:FilePermissions": 711,
  "File:FileType": "WAV",
  "File:MIMEType": "audio/x-wav",
  "RIFF:Encoding": 1,
  "RIFF:NumChannels": 2,
  "RIFF:SampleRate": 44100,
  "RIFF:AvgBytesPerSec": 176400,
  "RIFF:BitsPerSample": 16,
  "Composite:Duration": 0.833038548752834
}]

1 个答案:

答案 0 :(得分:2)

原始查询返回数组中的javascript对象。当您使用json.loads解析JSON时,您将获得列表中的dict。因此,要访问属性,请执行metadata[0]["File:FileSize"]

或者更改get_metadata方法以直接返回字典。

def get_metadata(self, *filenames):
    return json.loads(self.execute("-G", "-j", "-n", *filenames))[0]

不,json.loads不仅会返回词典。在他的评论中链接的table Tim指定了JSON到Python的翻译。