gjson icon indicating copy to clipboard operation
gjson copied to clipboard

[Question] How to create custom gjson.Result object?

Open o1o1o3 opened this issue 5 years ago • 1 comments

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,
}

o1o1o3 avatar Jun 22 '20 15:06 o1o1o3

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.

ozburo avatar Jul 20 '20 16:07 ozburo