In this json I want to change the value of an key from int to string in golang.
Input:
{
"id": 12345,
"wrapper": 898984,
"sections": {
"main": {
"type": 76899
}
},
"order": [
82322
]
}
Desired output:
{
"id": "12345",
"wrapper": "898984",
"sections": {
"main": {
"type": "76899"
}
},
"order": [
"82322"
]
}
CodePudding user response:
The most straightforward way is to create structs for both jsons. Then create function that converts one to another:
package main
import (
"encoding/json"
"fmt"
"strconv"
)
var input = `{ "id": 12345, "wrapper": 898984, "sections": { "main": { "type": 76899 } }, "order": [ 82322 ] }`
type DataWithInts struct {
ID int `json:"id"`
Wrapper int `json:"wrapper"`
Sections struct {
Main struct {
Type int `json:"type"`
} `json:"main"`
} `json:"sections"`
Order []int `json:"order"`
}
type MainStringsData struct {
Type string `json:"type"`
}
type SectionsStringsData struct {
Main MainStringsData `json:"main"`
}
type DataWithStrings struct {
ID string `json:"id"`
Wrapper string `json:"wrapper"`
Sections SectionsStringsData `json:"sections"`
Order []string `json:"order"`
}
func GetDataWithStrings(data *DataWithInts) *DataWithStrings {
var order []string
for _, v := range data.Order {
order = append(order, strconv.Itoa(v))
}
return &DataWithStrings{
ID: strconv.Itoa(data.ID),
Wrapper: strconv.Itoa(data.Wrapper),
Sections: SectionsStringsData{
Main: MainStringsData{
Type: strconv.Itoa(data.Sections.Main.Type),
},
},
Order: order,
}
}
func main() {
var dataInts DataWithInts
err := json.Unmarshal([]byte(input), &dataInts)
if err != nil {
panic(err)
}
dataStrings := GetDataWithStrings(&dataInts)
jsonData, err := json.Marshal(dataStrings)
if err != nil {
panic(err)
}
fmt.Println(string(jsonData))
}
more universal approach can use direct json parsing or reflect package.
P.S. To create structs, following site can be used: https://mholt.github.io/json-to-go/