minio / simdjson-go

Golang port of simdjson: parsing gigabytes of JSON per second
Apache License 2.0
1.8k stars 85 forks source link

How to handle values containing escaped JSON #80

Closed ForceFaction closed 1 year ago

ForceFaction commented 1 year ago

Hi, i'm trying to parse JSON with the following structure:

{
  "key" :  val,
  "list": [
              {"key1": {\"key2\":val1}}
              ...
          ]
}

I can't seem to find out how to get val1.

klauspost commented 1 year ago

Your JSON doesn't validate.

Do you mean

{
    "key": "val",
    "list": [{
        "key1": {
            "\"key2\"": "val1"
        }
    }]
}
ForceFaction commented 1 year ago

Hm sry, i actually mean:

{
    "key": "val",
    "list": [{
        "key1": "{\"key2\": \"val1\"}"
    }]
}
klauspost commented 1 year ago
func main() {
    // Parse JSON:
    pj, err := simdjson.Parse([]byte(`{
    "key": "val",
    "list": [{
        "key1": "{\"key2\": \"val1\"}"
    }]
}`), nil)
    if err != nil {
        log.Fatal(err)
    }

    iter := pj.Iter()
    list, err := iter.FindElement(nil, "list")
    if err != nil {
        log.Fatal(err)
    }
    arr, err := list.Iter.Array(nil)
    if err != nil {
        log.Fatal(err)
    }
    arr.ForEach(func(i simdjson.Iter) {
        if i.Type() != simdjson.TypeObject {
            return
        }
        elem, err := i.FindElement(nil, `key1`)
        if err != nil {
            return
        }
        fmt.Println(elem.Iter.String())
    })
    // Output:
    // {"key2": "val1"} <nil>
}
klauspost commented 1 year ago

{"key2": "val1"} is a string, so it is returned as that. It will not be parsed. You will have to do that once you have the value.