tsoding / haskell-json

Source Code for JSON Parser Video
https://www.youtube.com/watch?v=N9RUqGYuGfw
MIT License
169 stars 26 forks source link

2 questions #16

Open danielbom opened 4 years ago

danielbom commented 4 years ago
  1. What happening if I use this input? { "a": 1, "a": 2 }

  2. How I can get a value from parsed JSON? Ex: jsonParsed = runParser $ jsonValue "{ \"config\": { \"mode\": \"dev\" } }" jsonGet jsonParsed "config.mode"

dan323 commented 4 years ago

to query a JsonValue, you can implement a jmespath in haskell 👍

danielbom commented 4 years ago

A simple 'jsonValueByKey objectJson stringKey' it's enough to me.

dan323 commented 4 years ago

The json might not be a jsonObject, so we need something more involved than that. Nevertheless, at the end of the youtube video, if I remeber correctly, there are examples to query the json.

danielbom commented 4 years ago

Seeing ramda js, and sanctuary, I believe which a function to retrieve data from Json with this definition, it's a good improvement:

jsonPath :: JsonValue -> [String] -> Maybe JsonValue
jsonPath (JsonObject []) _ = Nothing
jsonPath (JsonObject (x:xs)) keys@(k:ks) =
  if k == fst x
  then jsonPath (snd x) ks
  else jsonPath (JsonObject xs) keys
jsonPath val [] = Just val
jsonPath _ _ = Nothing

Where the array of strings ('[String]') is the a array of keys to the value