Gojq modify query

Hello Everyone,

Learning how to program in Go and tried using GitHub - itchyny/gojq: Pure Go implementation of jq. I am having challenges on how to extract id from an api call below

{“id”: 1553,
“node_id”: “xxxxx”,
“name”: “xxxx-actions”,
“full_name”: “xxxx/xxxxx-actions”,
“private”: false,
“owner”: {
“login”: “xxxx”,
“id”: 4,
“node_id”: “xxxxxx”
}

}

But I do not know how to modify this part.

input := map[string]any{"foo": []any{1, 2, 3}}

I know this might look easy for others but I would appreciate any help the community can provide. Thank you in advance.

Regards,
Walter

Can you elaborate on what you don’t know how to modify? Are you asking how to get that example code from the readme so that you can modify it, or what the syntax of maps / slices are in Go, or maybe how to deserialize your example JSON into a map[string]any? Perhaps something else?

Not sure why you want to use /itchyny/gojq in my code – it’s a great package. But if you just want to change a value in json – lets say you’ve got it in a string. You did a http.Client get, the body contained a json string, and now you want to modify that string and make it the payload of a POST. I am not going to go over the http.Client part of this, but assume you already have the json string.

package main

import (
	"fmt"

	"github.com/tidwall/gjson"
	"github.com/tidwall/pretty"
	"github.com/tidwall/sjson"
)

var jIn string = `{"id":1553,"node_id":"xxxxx","name":"xxxx-actions","full_name":"xxxx/xxxxx-actions","private":false,"owner":{"login":"xxxx","id":4,"node_id":"xxxxxx"}}`

func main() {
	var err error
	res := gjson.Get(jIn, "owner.login")
	fmt.Println(res.Str)
	if jIn, err = sjson.Set(jIn, "owner.login", "Superman"); err != nil {
		panic(err)
	}
	jOut := pretty.Pretty([]byte(jIn))
	fmt.Println(string(jOut))

}

While I use /itchyny/gojq, my tools for json are tidwall (Josh Baker) · GitHub. Notice in this example I didn’t have to pull it in to a struct or map, it worked with the jIn json string directly. I was able to change the owner.login to Superman using sjson

Heres the go playground of that code:

Hello Rm,

I was trying to make gojq work, but you are right I just want to filter a json string. Your example fits my requirements.

Thank You,
Walter

Hi Sean,

Thanks for the reply, I am new to Go and still digesting data types.

Regards,
Walter

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.