itchyny / gojq

Pure Go implementation of jq
MIT License
3.26k stars 118 forks source link

Support strings with JSON as input #242

Closed shackra closed 7 months ago

shackra commented 7 months ago

I was expecting to use this project as a module and work over a parsed string that contains JSON, but it seems I need to bring my parsed data if I want to run a query

emanuele6 commented 7 months ago

You can parse a string containing JSON with the fromjson function from standard jq:

input:

{
  "foo": "[1,2,3,4]",
  "bar": "{\"baz\":[[\"bye\",{\"en\":\"bye\"}],[\"hello\",{\"it\":\"salve\"}]]}",
  "result": "{\"http\":{\"status\":200}}"
}

jq query:

{
  total: (.foo | fromjson | add),
  greeting: (.bar | first(fromjson.baz[] | select(.[0] == "hello")))[1].it,
  status: (.result | fromjson.http.status),
}

output:

{
  "total": 10,
  "greeting": "salve",
  "status": 200
}
itchyny commented 7 months ago

Maybe fromjson will help. I can't provide further instruction for feature request with no examples.

wader commented 7 months ago

@shackra You should be able to decode/unmarshal into a any using the standard library json package and use as input. Something like https://go.dev/play/p/xfaNhSczfSV