使用Golang修改JSON文件

时间:2017-05-01 03:38:45

标签: json file go file-writing

我正在尝试读取Golang中的JSON文件,修改此JSON文件,然后创建一个新的JSON文件/写入此JSON文件。我在网上看过几个样本,但似乎无法将两个和两个样本放在一起以获得所需的结果。我尝试在GO中制作自己的JSON str并修改它,但仍然失败了。

MyLabel.Text = MyTextBox.Text;
MyTextBox.Size = MyLabel.Size;

我已经多次尝试阅读该文件,下面是我最好的尝试:

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name    string
    Age     int
    Details interface{}
}

func main() {
    //I created a simple Json structure here to play with
    str := `{"name": "A",
        "age":20,
        "details": {"salary":100000000}
    }`
    var data Person

    err := json.Unmarshal([]byte(str), &data)
    if err != nil {
        panic(err)
    }

    //I make a map so that I can adjust the value of the salary
    details, ok := data.Details.(map[string]interface{})
    if ok {
        details["salary"] = 999999
    }
    //Change the other values of a Person
    data.Name = "B"
    data.Age = 19
    fmt.Println(data)

    //SAMPLE OUTPUT: {B 19 map[salary:999999]}
}

这是一个示例输出:

package main

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

/* Create the structure that follows the outline of the JSON file*/

type UserType struct {
    User []struct {
        CdbID     string `json:"cdb_id"`
        Firstname string `json:"firstname"`
        Lastname  string `json:"lastname"`
        Phone     int64  `json:"phone"`
        Email     string `json:"email"`
        Address   []struct {
            Street  string `json:"street"`
            City    string `json:"city"`
            Zip     string `json:"zip"`
            Country string `json:"country"`
        } `json:"address"`
        Authenticators []struct {
            Name  string `json:"name"`
            Phone int64  `json:"phone"`
        } `json:"authenticators"`
        VoiceSig            string `json:"voice_sig"`
        VoicesigCreatedTime string `json:"voicesig_created_time"`
        Status              string `json:"status"`
    } `json:"user"`
}

func main() {
    file, err := ioutil.ReadFile("user.json") //Read File
    if err != nil {
        fmt.Print("Error:", err)
    }

    var u UserType
    json.Unmarshal(file, &u)     //Parse the Json-encoded Data and store the results in u
    result, e := json.Marshal(u) //Returns the Json encoding of u into the variable result
    if e != nil {
        fmt.Println("error", err)
    }
    os.Stdout.Write(result) //The line of code golang.org uses to print  the Json encoding
}

我很困惑如何修改我想要的东西,特别是" Authenticators"上述样本输出。谢谢!

1 个答案:

答案 0 :(得分:1)

添加声明

type Authenticator struct {
    Name  string `json:"name"`
    Phone int64  `json:"phone"`
}

并更改

Authenticators []struct {
        Name  string `json:"name"`
        Phone int64  `json:"phone"`
} `json:"authenticators"`

Authenticators []Authenticator `json:"authenticators"`

然后,向第一个用户添加验证器:

u.User[0].Authenticators = append(u.User[0].Authenticators, Authenticator{
        Name: "John Doe",
        Phone: 1234567890,
})