tidwall / gjson

Get JSON values quickly - JSON parser for Go
MIT License
14.1k stars 846 forks source link

Get Bug when adding space #250

Closed itmaple closed 2 years ago

itmaple commented 2 years ago
{
  "name": {"first": "Tom", "last": "Anderson"},
  "age":37,
  "children": ["Sara","Alex","Jack"],
  "fav.movie": "Deer Hunter",
  "friends": [
    {"first": "Dale", "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]},
    {"first": "Roger", "last": "Craig", "age": 68, "nets": ["fb", "tw"]},
    {"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig", "tw"]}
  ]
}

With Space:

friends.#.{first, last, age}
[{"first":"Dale"},{"first":"Roger"},{"first":"Jane"}]

Without Space

friends.#.{first,last,age}
[{"first":"Dale","last":"Murphy","age":44},{"first":"Roger","last":"Craig","age":68},{"first":"Jane","last":"Murphy","age":47}]
tidwall commented 2 years ago

This is currently normal behavior in gjson. A space is considered a significant character in path components.

For this path:

friends.#.{first, last, age}

"first", " last", and " age" are used. Where last and age both have a single space prefix.

If your JSON included the space-prefixed keys, like such:

{
  "name": {"first": "Tom", "last": "Anderson"},
  "age":37,
  "children": ["Sara","Alex","Jack"],
  "fav.movie": "Deer Hunter",
  "friends": [
    {"first": "Dale", " last": "Murphy", " age": 44, "nets": ["ig", "fb", "tw"]},
    {"first": "Roger", " last": "Craig", " age": 68, "nets": ["fb", "tw"]},
    {"first": "Jane", " last": "Murphy", " age": 47, "nets": ["ig", "tw"]}
  ]
}

Then then response would be:

[{"first":"Dale"," last":"Murphy"," age":44},{"first":"Roger"," last":"Craig"," age":68},{"first":"Jane"," last":"Murphy"," age":47}]

When gjson was first introduced there was only simple paths like "name.first" or "friends.1.last", and spaces weren't much of a concern because it would be unusual to have a space in a path such as those.

But perhaps it may make more sense to ignore spaces, at least around the child paths in multipath components. It's probably not uncommon to have cases like you are describing.

itmaple commented 2 years ago

ok, thanks

natenho commented 2 years ago

@tidwall a suggestion could be to consider spaces around keys as an exceptional case, and an opt-in setting to enable it in case someone needs it.