Answer the question
In order to leave comments, you need to log in
How to add new key value to JSON?
There is a JSON file of users:
[
{
"id":1,
"score": 335
},
{
"id":2,
"score": 123
},
{
"id":3,
"score": 321
}
]
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
func main(){
file, err := os.Open("users.json")
if err != nil {
panic(err)
}
fileBytes, _ := ioutil.ReadAll(file)
var data []map[string]interface{}
json.Unmarshal(fileBytes, &data)
fmt.Println(data)
}
Answer the question
In order to leave comments, you need to log in
It is unclear whether the problem is adding a new user or writing to a file.
If it is adding, then you can do this:
package main
import (
"encoding/json"
"fmt"
"log"
)
type User struct {
ID int `json:"id"`
Score int `json:"score"`
}
func main() {
fileBytes := []byte(`[
{
"id":1,
"score": 335
},
{
"id":2,
"score": 123
},
{
"id":3,
"score": 321
}
]`)
var users []User
err := json.Unmarshal(fileBytes, &users)
if err != nil {
log.Fatalf("Failed to unmarshal: %s", err)
}
fmt.Printf("%#v\n", users)
newUser := User{
ID: 4,
Score: 1488,
}
users = addIfNotExist(users, newUser)
fmt.Printf("%#v\n", users)
// Дальше Marshal и сохранение в файле
}
func addIfNotExist(users []User, user User) []User {
for _, u := range users {
if u.ID == user.ID {
return users
}
}
return append(users, user)
}
1) add it to data
data["user2"]=...
2) serialize to byte slice json.Marshal
3) save byte slice to file
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question