Alex Klunniy Alex Klunniy - 5 months ago 19x
JSON Question

F# JSON parsing - How to get property using complex path (consisting of several propery names)

Is it possible to get property from JSON using complex path, like

Sample of JSON I used:

"prop1": {
"prop2": "value"

What I have want is to get property
there with its value
When I tried:

#r "../packages/FSharp.Data.2.3.0/lib/net40/FSharp.Data.dll"
open FSharp.Data
open FSharp.Data.JsonExtensions

let json = JsonValue.Load "SampleJson.json"

I got:

System.Exception: Didn't find property 'prop1.prop2' in {"prop1":{"prop2":"value"}}

I tried to write such method by my own, but it looks clumsy:

let rec tryGetChildValue (propNameSplitted : List<string>) (json:JsonValue) =
match propNameSplitted with
| [] -> None
| [x] -> json.TryGetProperty (x)
| x::xs ->
match json.TryGetProperty (x) with
| Some p -> tryGetChildValue xs (json.GetProperty(x))
| None -> None

let tryGetPropValue (propName: string) (json:JsonValue) =
let s = propName.Split '.' |> Array.toList
tryGetChildValue s json

let propName = "prop1.prop2"
let result = (tryGetPropValue propName json)


You can do that trivially with

open Newtonsoft.Json.Linq

let query json =
    let j = JObject.Parse json
    j.SelectToken "prop1.prop2" |> string

Obviously, there's no type safety with this approach, but that's the trade-off if you want to be able to query using arbitrary strings.