tidwall / gjson

Get JSON values quickly - JSON parser for Go
MIT License
13.95k stars 841 forks source link

anonymous array - bug? #266

Closed pavel-pimenov closed 2 years ago

pavel-pimenov commented 2 years ago
package main

import "github.com/tidwall/gjson"

const json = `{
   [
    {
      "firstName": "Janet", 
      "lastName": "McLaughlin", 
    }, {
      "firstName": "Elliotte", 
      "lastName": "Hunter", 
    }, {
      "firstName": "Jason", 
      "lastName": "Harold", 
    }
  ]
}`

func main() {
    result := gjson.Get(json, "*")
    for _, name := range result.Array() {
        println(name.String())
    }
}

output

Janet

Program exited.

https://go.dev/play/p/76doyDkWyn3

tidwall commented 2 years ago

Your json isn't valid. The array is nested in an object, but there is no key associated with the array. All object members should have one key for each value.

Your options are:

Make sure the json has a key.

{
  "my_key": [
    {
      "firstName": "Janet", 
      "lastName": "McLaughlin", 
    }, {
      "firstName": "Elliotte", 
      "lastName": "Hunter", 
    }, {
      "firstName": "Jason", 
      "lastName": "Harold", 
    }
  ]
}

Or, use the @valid modifier to ensure that gjson validates the invalid json prior to returning results.

result := gjson.Get(json, "@valid.*")