[Question] How to create custom gjson.Result object?
I want to create custom gjson.Result object to compare it with other gjson.Result.
How to create it for slice? I have a slice:
mySlice := []string{
"hello",
"world"
}
And i want to get the Result object for this slice.
Is this correct way to do this?
jsonStr, _ := json.Marshal(tmp)
result = gjson.Result{
Type: gjson.JSON,
Raw: string(jsonStr),
Str: "",
Num: 0,
Index: 0,
}
Just use inbuilt Parse method from your JSON string, you don't need to create a slice, marshall it to a JSON string, and then create a gjson.Result literal.
var json = `{"name":{"first":"Janet","last":"Prichard"},"age":47}`
r := gjson.Parse(json) // "r" is a gjson.Result
fmt.Println(r.Get("name.first"))
If you're problem is equivalency comparisons for tests etc., I haven't had the need to do direct gjson.Result comparisions. I would simply convert the Result to basic types and test those.
Also, there is the sister project sjson that you can use to generate/modify JSON strings, that's where I got the sample JSON string above.