How to extract an object from a request (json format)?

Hello I’m trying to parse a request to json format, I know I can use json.NewDecoder(r.Body).Decode(&myStruct) but in my case I have different objects in the request and I need to parse some of them in a struct and others in another structs, let me explain it:

From the cliente I recieve something like this:

map[features[f7]:[Presencia en Medios] lat:[19.39068] products[2][title]:[tortas] features[f10]:[Estrategia] addr:[Chabacano 7, San Fernando, 52765 Naucalpan de Juárez, Méx., Mexico] title:[titulo del app] slogan:[slogan ] products[1][title]:[arroz] actions[]:[0 call contact reservation video shop register] products[0][title]:[comida] stars[star1][Desc]:[] stars[star2][Name]:[] stars[star2][Desc]:[] stars[star2][Img]:[pizza.jpg] stars[star1][Name]:[] stars[star1][Img]:[pasta.jpg] lng:[-99.2836985] email:[]]

I know is a little messy, the point is that I need to access for example to the products key and parses it in a struct, then I need to access the stars key and parses it in another struct and so on… But i don’t know how to get an specific part of the request when I tryo do r.Form["products"] it returns an empty array.

i think that you can read the json request into a map[string]interface{} variable and parse that.

The struct you deserialize into can consist of other structs.

type product struct {
    Title string
    // ...

type star struct {
    Descr string
    // ...

type outer struct {
    Products []product
    Stars []star
    // ...

// ...
var myStruct outer
err = json.NewDecoder(r.Body).Decode(&myStruct)
// ...

Does that help?

Take a look at json.RawMessage. It can be part of top level structures and unmarshalled later, when you’ve decided based on the top level data what kind of structs are needed for the nested data.


Yes man that helps me a lot, thanks.

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