on master help sign in
Add handling of the leading '_' to 'fromJSON'
2aa2513Eduard Sergeev
Data/Aeson/Generic.hs+8−5
@@ -112,6 +112,13 @@ toJSON = toJSON_generic
112 remap f = Object . hashMap (f . fromJust . cast) toJSON $ m
112 remap f = Object . hashMap (f . fromJust . cast) toJSON $ m
113
113
114
114
115+-- Skip leading '_' in field name so we can use keywords
116+-- etc. as field names.
117+mungeField :: String -> Text
118+mungeField ('_':cs) = pack cs
119+mungeField cs = pack cs
120+
121+
115toJSON_generic :: (Data a) => a -> Value
122toJSON_generic :: (Data a) => a -> Value
116toJSON_generic = generic
123toJSON_generic = generic
117 where
124 where
@@ -146,10 +153,6 @@ toJSON_generic = generic
146 encodeArgs' [] js = Array . V.fromList $ js
153 encodeArgs' [] js = Array . V.fromList $ js
147 encodeArgs' ns js = object $ zip (map mungeField ns) js
154 encodeArgs' ns js = object $ zip (map mungeField ns) js
148
155
149− -- Skip leading '_' in field name so we can use keywords
150− -- etc. as field names.
151− mungeField ('_':cs) = pack cs
152− mungeField cs = pack cs
153
156
154fromJSON :: (Data a) => Value -> Result a
157fromJSON :: (Data a) => Value -> Result a
155fromJSON = parse parseJSON
158fromJSON = parse parseJSON
@@ -284,7 +287,7 @@ parseJSON_generic j = generic
284 -- Select the named fields from a JSON object.
287 -- Select the named fields from a JSON object.
285 selectFields fjs = mapM sel
288 selectFields fjs = mapM sel
286 where sel f = maybe (modFail "parseJSON" $ "field does not exist " ++
289 where sel f = maybe (modFail "parseJSON" $ "field does not exist " ++
287− f) return $ Map.lookup (pack f) fjs
290+ f) return $ Map.lookup (mungeField f) fjs
288
291
289 -- Count how many arguments a constructor has. The value x is
292 -- Count how many arguments a constructor has. The value x is
290 -- used to determine what type the constructor returns.
293 -- used to determine what type the constructor returns.