baronsec
baronsec

Reputation: 234

Changing values in json file with go

I've got a small json file

{
    "first": "",
    "second": ""
}

and I want to ocasionally modify its values. I managed to open the file using Unmarshal but I don't know how to change its values.

package main

import (
    "encoding/json"
    "io/ioutil"
)

type Data struct {
    First string `json:"first"`
    Second string `json:"second"`
}

func main() {

    //read json file with io/ioutil
    file, _ := ioutil.ReadFile("temp.json")

    var data Data

    json.Unmarshal(file, &data)
}

I saw that you can Marshal and it should change the json file by the Data struct but I don't want to rewrite the file everytime just to modify a single value. Is there a way to change by variable or I do have to use the Marshal function?

Upvotes: 0

Views: 1383

Answers (1)

Ggicci
Ggicci

Reputation: 835

You have to load the entire file into memory, make changes and write back to the file. In order to manipulate JSON structured objects more easily, add your encode & decode steps:

1. JSON file    (A) ----- read -----------> file content (B, text)
2. file content (B) ----- json decode ----> json object  (C, structured)
3. json object  (C) ----- change value ---> json object  (D)
4. json object  (D) ----- json encode ----> new content  (E)
5. new content  (E) ----- write ----------> JSON file    (F)

If you are asking about "if it possible to partially update the file itself", it can be a duplicate of How to partially update JSON file.

The APIs you can use in Go that the package encoding/json provided are:

Upvotes: 1

Related Questions