L
L
linuxoid_inrus2020-11-10 09:20:16
go
linuxoid_inrus, 2020-11-10 09:20:16

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
  }
]


I get users like this:
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)

}


How to add a new user to the file if I can't find it by ID?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Samsonov, 2020-11-10
@linuxoid_inrus

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)
}

https://play.golang.org/p/ytITBXxE7NB
I will duplicate the recommendations from the comment to the question:
1) Use structures to work with data, not map and empty interfaces. It's idiomatically closer to Golang and more convenient
2) Always handle errors. If the ReadAll function throws an error, there is no point in trying to Unmarshal. And it's hard to understand what happened when the error is hushed up

D
Dasha Tsiklauri, 2020-11-10
@dasha_programmist

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 question

Ask a Question

731 491 924 answers to any question