jsongoencoding-json-go

Parse json body array sent in POST request and print


I am having one issue while reading the json array. Need help for below query.

Request Json :

{ "httpReq": {
"username": "1234567890",
"password": "1234567890",
"number": "123456"
}
}

Response Json :

{ "httpResp": {
    "status": "Pass",
    "message": "great"
    }
    }

Below was my code: If i am passing the json object below its working, but i need to send "httpReq" in json.

package main

import (
    "encoding/json"
    "fmt"
)


type people struct {
    Username string `json:"username"`
    Password string `json:"password"`
    Number string `json:"number"`
    
}

type peopleread struct {
    Collection []people
}

func main() {
    text := `{
    "username": "1234567890",
    "password": "1234567890",
    "number": "123456"
    
}`
    textBytes := []byte(text)

    //people1 := people{}
    var people2 people
    err := json.Unmarshal(textBytes, &people2)
    if err != nil {
        fmt.Println(err)
        return
    }
    Username := people2.Username
    Password := people2.Password
    Number := people2.Number
        fmt.Println(Username)
        fmt.Println(Password)
        fmt.Println(Number) 
}

Solution

  • To unmarshal with httpReq field you have to handle this.

    Create a struct to your wrap your request body like json

    type HttpReq struct{
       HttpReq people `json:"httpReq"`
    }
    

    Then use unmarshal

    var httpReq HttpReq
    err := json.Unmarshal(textBytes, &httpReq)
    

    Full code in Go playground here