educative.io

Educative

How to add new filed in json data

is there a way to add new filed in the Json data i have tried but it is not working

package main
import (
	"fmt"
	"encoding/json"
	)
type Person struct {
	Name string `json:"personName"`
	Age int `json:"personAge"`
}
func (p Person) MarshalJSON() ([]byte, error) {
	n := struct{
		Person Person
		dummy string
	}{
		Person: p,
		dummy: "dummy",
	}
	return json.Marshal(n)
}
func main() {
	b := []byte(`{"personName": "Obama", "personAge": 57}`)
	p := []Person{}
	// Unmarshalling
	json.Unmarshal(b, &p)
	fmt.Println(p)
	// Marshalling
	js, _ := json.Marshal(p)
	fmt.Printf("%s\n", js)
}

Hi @vikas_mastud1

This is Maham Amjad from Educative. I noticed your feedback here, and I’m glad you reached out to us.

What I understand from your question is you want to add another field in JSON data like personName and personAge.

To add the data, first, we have to make an entry in the Person struct as well. Below is an example:

package main
import (
  "fmt"
  "encoding/json"
)

type Person struct {
  Name string `json:"personName"`
  Age int `json:"personAge"`
  Married bool `json:"married"`
}

func main() {
  b := []byte(`{"personName": "Obama", "personAge": 57, "married": true}`)
  var p Person
  // Unmarshalling
  json.Unmarshal(b, &p)
  fmt.Println(p)
  // Marshalling
  js, _ := json.Marshal(p)
  fmt.Printf("%s\n", js)
}

Let us know if that’s not what you have asked for. Thank you for reaching out! Please feel free to reach out if you have any other queries or concerns.

Best Regards,
Maham Amjad| Developer Advocate
Educative Inc.