如何在Haskell中解析exiftool JSON输出的示例

时间:2010-01-18 21:03:15

标签: json haskell exiftool

我无法理解任何文档。有人可以提供一个示例,说明如何使用Haskell模块exiftool解析以下缩短的Text.JSON输出?使用命令exiftool -G -j <files.jpg>生成数据。

[{
  "SourceFile": "DSC00690.JPG",
  "ExifTool:ExifToolVersion": 7.82,
  "File:FileName": "DSC00690.JPG",
  "Composite:LightValue": 11.6
},
{
  "SourceFile": "DSC00693.JPG",
  "ExifTool:ExifToolVersion": 7.82,
  "File:FileName": "DSC00693.JPG",
  "EXIF:Compression": "JPEG (old-style)",
  "EXIF:ThumbnailLength": 4817,
  "Composite:LightValue": 13.0
},
{
  "SourceFile": "DSC00694.JPG",
  "ExifTool:ExifToolVersion": 7.82,
  "File:FileName": "DSC00694.JPG",
  "Composite:LightValue": 3.7
}]

2 个答案:

答案 0 :(得分:10)

嗯,最简单的方法是从json包中取回一个JSValue,就像这样(假设你的数据在text.json中):

Prelude Text.JSON> s <- readFile "test.json"
Prelude Text.JSON> decode s :: Result JSValue
Ok (JSArray [JSObject (JSONObject {fromJSObject = [("SourceFile",JSString (JSONString {fromJSString = "DSC00690.JPG"})),("ExifTool:ExifToolVersion",JSRational False (391 % 50)),("File:FileName",JSString (JSONString {fromJSString = "DSC00690.JPG"})),("Composite:LightValue",JSRational False (58 % 5))]}),JSObject (JSONObject {fromJSObject = [("SourceFile",JSString (JSONString {fromJSString = "DSC00693.JPG"})),("ExifTool:ExifToolVersion",JSRational False (391 % 50)),("File:FileName",JSString (JSONString {fromJSString = "DSC00693.JPG"})),("EXIF:Compression",JSString (JSONString {fromJSString = "JPEG (old-style)"})),("EXIF:ThumbnailLength",JSRational False (4817 % 1)),("Composite:LightValue",JSRational False (13 % 1))]}),JSObject (JSONObject {fromJSObject = [("SourceFile",JSString (JSONString {fromJSString = "DSC00694.JPG"})),("ExifTool:ExifToolVersion",JSRational False (391 % 50)),("File:FileName",JSString (JSONString {fromJSString = "DSC00694.JPG"})),("Composite:LightValue",JSRational False (37 % 10))]})])

这只是给你一个通用的json Haskell数据类型。

下一步是为您的数据定义一个自定义Haskell数据类型,并为其编写一个JSON实例,在上面的JSValue和您的类型之间进行转换。

答案 1 :(得分:2)

感谢所有人。根据您的建议,我能够将以下内容组合在一起,将JSON转换回名称 - 值对。

data Exif = 
    Exif [(String, String)]
    deriving (Eq, Ord, Show)

instance JSON Exif where
    showJSON (Exif xs) = showJSONs xs
    readJSON (JSObject obj) = Ok $ Exif [(n, s v) | (n, JSString v) <- o]
        where 
            o = fromJSObject obj
            s = fromJSString

不幸的是,似乎库无法将JSON直接转换回简单的Haskell数据结构。在Python中,它是一个单行:json.loads(s)