jsonparser icon indicating copy to clipboard operation
jsonparser copied to clipboard

Dynamic Json Construction

Open ahambrahma opened this issue 5 years ago • 2 comments

I am working on a project where we are required to build dynamic json objects from a map of dotted json paths and their values. We should be able to convert the constructed json object into an already defined struct.

For ex:

Given an input Map:

"success": true "data.name": "shubham" "data.age": 21 "data.height": 172

We should be able to generate this json object

{ "success": true, "data" : { "name" : "shubham", "age": 21, "height": 172 } }

and convert it into UserResponse

type UserResponse struct { Success bool json:"success" Data User json:"data" }

type User struct { Name string json:"name" Age int json:"age" Height int json:"height"
}

Can someone help with how we can achieve this using jsonparser ?

ahambrahma avatar Oct 07 '20 06:10 ahambrahma

Hi Guys,

Any update on this?

ahambrahma avatar Oct 28 '20 12:10 ahambrahma

Hi @shubham140395,

I didn't used jsonparser, but one solution I have used is to unmarshal it to UserResponse struct like this.

var userResponse UserResponse

err := json.Unmarshal([]byte(jsondata), &userResponse)

Hope this helps to you.

cp-sumi-k avatar Nov 27 '20 11:11 cp-sumi-k