Filter JSON like Javascript in Go

I am trying to filter JSON but have not found any simple way to do this in Go. Is there a built in way to do this? Or how can I achieve this using Go? Preferable without using struct.

With map instead of struct, as desired:

This one’s a little cleaner without predicate code duplication

1 Like

On the right track, thank you! But I do not understand how I can get valid JSON in a variable out of this?

[]main.Item{main.Item{"row":"Home", "sub":"home"}, main.Item{"row":"Test", "sub":"home"}}

Like

[{"sub":"home","row":"Home"},{"sub":"home","row":"Test"}]

Is there a reason you wouldn’t just json.Marshal it? Adding to @mje’s excellent last playground link, you could do something like this:

json, err := json.Marshal(filter(makePredicate("home"), data))
if err != nil {
	fmt.Println("Error:", err.Error)
}

fmt.Printf("%s\n", json)

Which nets you:

[{“row”:“Home”,“sub”:“home”},{“row”:“Test”,“sub”:“home”}]

Here’s an updated version of Jeff’s solution:

2 Likes

Yes, my lack of knowledge. But your few lines added to @mje does help me. Thank you both!

I particularly like the comment about checking for errors!

2 Likes

This may be a dumb question. But is there a possibility to move the error checking into func filter(predicate func(Item)?

Dean’s error checking is to handle errors from json.Marshal. What errors do you expect in filter, which runs before the call to json.Marshal? Explicit error checking is fundamental to Go coding, so you shouldn’t try to avoid it if that is the basis of your question.

1 Like