Modifying JSON file using Golang

huangapple go评论92阅读模式
英文:

Modifying JSON file using Golang

问题

我正在尝试在Golang中读取一个JSON文件,修改该JSON文件,然后创建一个新的JSON文件/覆盖该JSON文件。我在网上看到了几个示例,但似乎无法将它们结合起来得到所需的结果。我尝试在GO中创建自己的JSON字符串并对其进行修改,但仍然失败了。

以下是我最好的尝试之一,读取文件的代码:

package main

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

/* 创建与JSON文件大纲相符的结构体 */

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") // 读取文件
	if err != nil {
		fmt.Print("Error:", err)
	}

	var u UserType
	json.Unmarshal(file, &u)     // 解析JSON编码的数据并将结果存储在u中
	result, e := json.Marshal(u) // 将u编码为JSON格式并存储在result中
	if e != nil {
		fmt.Println("error", err)
	}
	os.Stdout.Write(result) // 这是golang.org用于打印JSON编码的代码行
}

这是一个示例输出:

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

我只是对如何修改我想要的内容感到困惑,特别是上述示例输出中的"Authenticators"部分。谢谢!

英文:

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

得分: 2

添加一个声明

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,
})
英文:

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

huangapple
  • 本文由 发表于 2017年5月1日 11:38:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/43713952.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定