使用Golang修改JSON文件

I am attempting to read in a JSON file in Golang, modifying this JSON file, and then creating a new JSON file/writing over this JSON file. I have seen several samples online, but can't seem to put two and two together to get the required result. I tried just making my own JSON str in GO and modifying that, but have still failed.

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

I have made several attempts with reading the file, below is my best attempt:

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
}

This is a sample output:

{
    "user": [{
        "cdb_id":"",
        "firstname":"Tom",
        "lastname":"Bradley",
        "phone":14155555555,
        "email":"tom@gmail.com",
        "address":[{
            "street":"4343 shoemaker ave",
            "city":"Brea",
            "zip":"92821",
            "country":"USA"
        }],
        "authenticators":[{
            "name":"Lisa Hayden",
            "phone":15625555555
        },{
            "name":"Pavan M",
            "phone":17145555555
        }],
        "voice_sig":"242y5-4546-555kk54-437879ek545",
        "voicesig_created_time":"2017-08-02T21:27:44+0000",
        "status":"verified"
    }]
}

I am just confused on how to modify what I want, specifically the "Authenticators" of the aforementioned sample output. Thanks!

1个回答



添加声明</ p>

  type Authenticator struct {
名称字符串json: “ name”
Phone int64json:“ phone”
}
</ code> </ pre>

并更改</ p>

  Authenticators [] struct {
名称字符串json:“ name”
Phone int64json:“ phone”
}json:“ authenticators”
</ code> </ pre>

到</ p>

 身份验证者[] Authenticatorjson:“ authenticators”
</ code> </ pre>

然后, 将验证者添加到第一个用户:</ p>

  u.User [0] .Authenticators = append(u.User [0] .Authenticators,Authenticator {
Name:“ John Doe“,
电话:1234567890,
})
</ code> </ pre>
</ div>

展开原文

原文

Add a declaration

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

and change

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

to

Authenticators []Authenticator `json:"authenticators"`

Then, to add an authenticator to the first user:

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

douye9175
douye9175 我很想念你u.User是一片片。 我已经在上面修改了我的代码。
3 年多之前 回复
doujian3401
doujian3401 我了解您的代码,但是除非我搞砸了,否则某些问题将无法解决。 我收到错误消息:“#命令行参数./json.go:48:u.User.Authenticators未定义”。 我是否应该更改UserType的结构,而不是用一系列细分的较小结构代替该文本块? 谢谢,我很重视您的回复!
3 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐