itchyny / gojq

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

Example of retrieving JSON or unmarshalled object #245

Closed lordofscripts closed 5 months ago

lordofscripts commented 5 months ago

I am trying to use GoJQ in my program, not as a command-line type query, but to efficiently query a LARGE JSON object.

The examples are more CLI-oriented and the methods appear to return iterators. Is there a way to run a query on that large object and as return, instead of a plain value or iterator, return either the resulting JSON sub-object that I can un-marshal?

itchyny commented 5 months ago

You can unmarshal your json object into any type and pass it to gojq. I'm not sure what you actually need, without some sample code you want to achieve.

lordofscripts commented 5 months ago

What I meant was that, if I passed my entire JSON to GoJQ, when I query for a subset of the whole, I would like that JSON subset as the query return rather than an iterator.

bytes, err := os.ReadFile(JSON_FILE)
data := map[string]any{}
dec := json.NewDecoder(strings.NewReader(string(bytes)))
dec.Decode(&data)
query, err := gojq.Parse(`.revisions[0].categories[] | select(.code=="5")`)
iter := query.Run(data)

This gets me to iterate through each individual Member. But what if rather than that (the iterator), I would like something I can i Marshall (given that I know the underlying data model of the result). Is that possible with GoJQ? I am stumped at that point.

wader commented 5 months ago

You can use the iterator to collect all values, call Next() until it's done. Something like this https://go.dev/play/p/UVvb2pMhwdk

itchyny commented 5 months ago

Right, you can collect the results into a slice. The output of jq query is essentially an iterator, which may emit nothing (consider your query does not match any categories), or may emit infinite number of results (consider repeat(0) or range(infinite)). It is up to you how to handle these cases.