Golang中如何将JSON数据追加到另一个JSON文件

Golang中如何将JSON数据追加到另一个JSON文件 你好

我们能否将JSON推入JSON?

playGround:https://play.golang.org/p/HSE46L9h_Yb

package main

import (
	"encoding/json"
	"github.com/emirpasic/gods/maps/linkedhashmap"
)
func GetGames(){
	type GameDetails struct {
		Name         string   `json:"nm"`
		Id                int       `json:"id"`
		ThumbUrl   string  `json:"tmb_ul"`
		Requirement   linkedhashmap.Iterator  `json:"reqs,omitempty"`
	}

	games := new(GameDetails)

	games.Name = "Stronghold Crusader"
	games.Id =1120
	games.ThumbUrl="picture/eeee.jpg"



	//this is JSON in database:
	requirement:=`{"Hard disk space":"3 GB","Memory":"768 MB","Operating system":"Windows XP/Vista/7","Processor":"Intel Pentium III 700 MHz or AMD Athlon 500 MHz K6","Sound device":"compatible with DirectX","Video card":"128 MB (GeForce 5700/Radeon 9600)"}`


	n := linkedhashmap.New()
	err:=n.FromJSON([]byte(requirement))
	if err != nil {
		print(err)
	}
	result:=n.Iterator()
	games.Requirement=result

	mkJson,err:= json.Marshal(games)
	if err != nil {
	print(err)
	 }
	print(string(mkJson))
}

我已经尝试过这种方式但不起作用(linkedhashmap)

现在,如何将"requirement"添加到games中? 1- 反序列化为map[string]string不起作用,因为我希望保持JSON原样

  • 从Golang版本1开始我们就无法对map进行排序 2- 反序列化为struct也不起作用,因为如果"requirement" JSON中添加了字段,我们无法自动添加结构体字段

提前感谢。


更多关于Golang中如何将JSON数据追加到另一个JSON文件的实战教程也可以访问 https://www.itying.com/category-94-b0.html

9 回复

谢谢,但这没有用, 我想要保持顺序的映射

更多关于Golang中如何将JSON数据追加到另一个JSON文件的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在映射中不存在顺序,无论是在 Go 语言中还是在 JSON 中。

感谢acim,你完全解决了我的问题。

https://play.golang.org/p/omsDQzDQ8h3

我只是好奇。为什么顺序很重要?http://www.json.org/ 声明如下:

一个对象是一个无序的键值对集合。对象以 {(左大括号)开始,以 }(右大括号)结束。每个键后跟 :(冒号),键值对之间用 ,(逗号)分隔。

谢谢,但如果我们在 JSON 中添加一个额外的字段,而在代码中没有添加,会发生什么情况?像这样:

{"shader":3 ,"Hard disk space":"3 GB","Memory":"768 MB","Operating system":"Windows XP/Vista/7","Processor":"Intel Pentium III 700 MHz or AMD Athlon 500 MHz K6","Sound device":"compatible with DirectX","Video card":"128 MB (GeForce 5700/Radeon 9600)"}

你可以这样做:https://play.golang.org/p/PzN7nByVbag

package main

import (
	"encoding/json"
)

func main() {
	GetGames()
}
func GetGames() {
	type GameDetails struct {
		Name          string `json:"nm"`
		Id            int    `json:"id"`
		ThumbUrl      string `json:"tmb_ul"`
		HardDiskSpace string `json:"Hard disk space"`
		Memory        string `json:"Memory"`
		OperatingSystem string `json:"Operating system"`
	}

	games := new(GameDetails)

	games.Name = "Stronghold Crusader"
	games.Id = 1120
	games.ThumbUrl = "picture/eeee.jpg"

	//这是数据库中的JSON:
	requirement := `{"Hard disk space":"3 GB","Memory":"768 MB","Operating system":"Windows XP/Vista/7","Processor":"Intel Pentium III 700 MHz or AMD Athlon 500 MHz K6","Sound device":"compatible with DirectX","Video card":"128 MB (GeForce 5700/Radeon 9600)"}`

	err := json.Unmarshal([]byte(requirement), games)
	if err != nil {
		print(err)
	}

	mkJson, err := json.Marshal(games)
	if err != nil {
		print(err)
	}
	print(string(mkJson))
}

你好。它们会被忽略。但你也可以这样做。https://play.golang.org/p/JjasqJEVDKk

package main

import (
	"encoding/json"
)

func main() {
	GetGames()
}
func GetGames() {
	type GameDetails struct {
		Name        string            `json:"nm"`
		Id          int               `json:"id"`
		ThumbUrl    string            `json:"tmb_ul"`
		Requirement map[string]string `json:"reqs,omitempty"`
	}

	games := new(GameDetails)

	games.Name = "Stronghold Crusader"
	games.Id = 1120
	games.ThumbUrl = "picture/eeee.jpg"

	//this is JSON in database:
	requirement := `{"Hard disk space":"3 GB","Memory":"768 MB","Operating system":"Windows XP/Vista/7","Processor":"Intel Pentium III 700 MHz or AMD Athlon 500 MHz K6","Sound device":"compatible with DirectX","Video card":"128 MB (GeForce 5700/Radeon 9600)"}`

	err := json.Unmarshal([]byte(requirement), &games.Requirement)
	if err != nil {
		print(err)
	}

	mkJson, err := json.Marshal(games)
	if err != nil {
		print(err)
	}
	print(string(mkJson))
}

在Golang中,你可以使用json.RawMessage来保持JSON数据的原始格式,这样既能保持字段顺序,又能灵活处理动态字段。以下是修改后的代码示例:

package main

import (
	"encoding/json"
	"fmt"
)

func GetGames() {
	type GameDetails struct {
		Name        string          `json:"nm"`
		Id          int             `json:"id"`
		ThumbUrl    string          `json:"tmb_ul"`
		Requirement json.RawMessage `json:"reqs,omitempty"`
	}

	games := GameDetails{
		Name:     "Stronghold Crusader",
		Id:       1120,
		ThumbUrl: "picture/eeee.jpg",
	}

	// 原始JSON数据
	requirement := `{"Hard disk space":"3 GB","Memory":"768 MB","Operating system":"Windows XP/Vista/7","Processor":"Intel Pentium III 700 MHz or AMD Athlon 500 MHz K6","Sound device":"compatible with DirectX","Video card":"128 MB (GeForce 5700/Radeon 9600)"}`

	// 将JSON字符串转换为RawMessage
	games.Requirement = json.RawMessage(requirement)

	mkJson, err := json.Marshal(games)
	if err != nil {
		fmt.Println("JSON编码错误:", err)
		return
	}
	fmt.Println(string(mkJson))
}

func main() {
	GetGames()
}

输出结果:

{"nm":"Stronghold Crusader","id":1120,"tmb_ul":"picture/eeee.jpg","reqs":{"Hard disk space":"3 GB","Memory":"768 MB","Operating system":"Windows XP/Vista/7","Processor":"Intel Pentium III 700 MHz or AMD Athlon 500 MHz K6","Sound device":"compatible with DirectX","Video card":"128 MB (GeForce 5700/Radeon 9600)"}}

如果你需要将多个游戏数据追加到现有JSON文件中,可以使用以下代码:

package main

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

func AppendGameToFile(filename string, newGame GameDetails) error {
	// 读取现有文件内容
	file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0644)
	if err != nil {
		return err
	}
	defer file.Close()

	// 解码现有数据
	var games []GameDetails
	decoder := json.NewDecoder(file)
	err = decoder.Decode(&games)
	if err != nil && err.Error() != "EOF" {
		return err
	}

	// 追加新游戏
	games = append(games, newGame)

	// 重置文件指针并截断文件
	file.Seek(0, 0)
	file.Truncate(0)

	// 编码并写回文件
	encoder := json.NewEncoder(file)
	encoder.SetIndent("", "  ")
	return encoder.Encode(games)
}

type GameDetails struct {
	Name        string          `json:"nm"`
	Id          int             `json:"id"`
	ThumbUrl    string          `json:"tmb_ul"`
	Requirement json.RawMessage `json:"reqs,omitempty"`
}

func main() {
	requirement := `{"Hard disk space":"3 GB","Memory":"768 MB","Operating system":"Windows XP/Vista/7","Processor":"Intel Pentium III 700 MHz or AMD Athlon 500 MHz K6","Sound device":"compatible with DirectX","Video card":"128 MB (GeForce 5700/Radeon 9600)"}`

	newGame := GameDetails{
		Name:        "Stronghold Crusader",
		Id:          1120,
		ThumbUrl:    "picture/eeee.jpg",
		Requirement: json.RawMessage(requirement),
	}

	err := AppendGameToFile("games.json", newGame)
	if err != nil {
		fmt.Println("追加到文件错误:", err)
	}
}

json.RawMessage保持了原始JSON的字节序列,包括字段顺序,同时允许你在不预定义完整结构的情况下处理动态JSON数据。

回到顶部