使用结构字段(不是 json 键)将结构写入 Json 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24770403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write Struct to Json File using Struct Fields (not json keys)
提问by Joe Bergevin
How can I read a json file into a struct, and then Marshal it back out to a json string with the Struct fields as keys (rather than the original json keys)?
如何将一个 json 文件读入一个结构体,然后将其编组回一个以 Struct 字段作为键(而不是原始 json 键)的 json 字符串?
(see Desired Output to Json Filebelow...)
(见Desired Output to Json File下文...)
Code:
代码:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
)
type Rankings struct {
Keyword string `json:"keyword"`
GetCount uint32 `json:"get_count"`
Engine string `json:"engine"`
Locale string `json:"locale"`
Mobile bool `json:"mobile"`
}
func main() {
var jsonBlob = []byte(`
{"keyword":"hipaa compliance form", "get_count":157, "engine":"google", "locale":"en-us", "mobile":false}
`)
rankings := Rankings{}
err := json.Unmarshal(jsonBlob, &rankings)
if err != nil {
// nozzle.printError("opening config file", err.Error())
}
rankingsJson, _ := json.Marshal(rankings)
err = ioutil.WriteFile("output.json", rankingsJson, 0644)
fmt.Printf("%+v", rankings)
}
Output on screen:
屏幕输出:
{Keyword:hipaa compliance form GetCount:157 Engine:google Locale:en-us Mobile:false}
Output to Json File:
输出到 Json 文件:
{"keyword":"hipaa compliance form","get_count":157,"engine":"google","locale":"en-us","mobile":false}
Desired Output to Json File:
期望输出到 Json 文件:
{"Keyword":"hipaa compliance form","GetCount":157,"Engine":"google","Locale":"en-us","Mobile":false}
回答by Momer
If I understand your question correctly, all you want to do is remove the json tags from your struct definition.
如果我正确理解您的问题,您要做的就是从结构定义中删除 json 标签。
So:
所以:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
)
type Rankings struct {
Keyword string
GetCount uint32
Engine string
Locale string
Mobile bool
}
func main() {
var jsonBlob = []byte(`
{"keyword":"hipaa compliance form", "get_count":157, "engine":"google", "locale":"en-us", "mobile":false}
`)
rankings := Rankings{}
err := json.Unmarshal(jsonBlob, &rankings)
if err != nil {
// nozzle.printError("opening config file", err.Error())
}
rankingsJson, _ := json.Marshal(rankings)
err = ioutil.WriteFile("output.json", rankingsJson, 0644)
fmt.Printf("%+v", rankings)
}
Results in:
结果是:
{Keyword:hipaa compliance form GetCount:0 Engine:google Locale:en-us Mobile:false}
And the file output is:
文件输出是:
{"Keyword":"hipaa compliance form","GetCount":0,"Engine":"google","Locale":" en-us","Mobile":false}
Running example at http://play.golang.org/p/dC3s37HxvZ
在http://play.golang.org/p/dC3s37HxvZ运行示例
Note: GetCount shows 0, since it was read in as "get_count". If you want to read in JSON that has "get_count"vs. "GetCount", but output "GetCount"then you'll have to do some additional parsing.
注意:GetCount 显示 0,因为它是作为"get_count". 如果您想读取具有"get_count"vs. 的JSON "GetCount",但要输出,"GetCount"则您必须进行一些额外的解析。
See Go- Copy all common fields between structsfor additional info about this particular situation.
有关此特定情况的其他信息,请参阅Go- Copy all common fields between structs。
回答by boulavard
Try to change the json format in the struct
尝试更改struct中的json格式
type Rankings struct {
Keyword string `json:"Keyword"`
GetCount uint32 `json:"Get_count"`
Engine string `json:"Engine"`
Locale string `json:"Locale"`
Mobile bool `json:"Mobile"`
}
回答by accnameowl
An accourance happened by just using json.Marshal() / json.MarshalIndent(). It overwrites the existing file, which in my case was suboptimal. I just wanted to add content to current file, and keep old content.
仅使用 json.Marshal() / json.MarshalIndent() 就发生了准确性。它覆盖了现有文件,这在我的情况下是次优的。我只想将内容添加到当前文件,并保留旧内容。
This writes data through a buffer, with bytes.Buffer type.
这通过缓冲区写入数据,类型为 bytes.Buffer。
This is what I gathered up so far:
这是我到目前为止收集的内容:
package srf
import (
"bytes"
"encoding/json"
"os"
)
func WriteDataToFileAsJSON(data interface{}, filedir string) (int, error) {
//write data as buffer to json encoder
buffer := new(bytes.Buffer)
encoder := json.NewEncoder(buffer)
encoder.SetIndent("", "\t")
err := encoder.Encode(data)
if err != nil {
return 0, err
}
file, err := os.OpenFile(filedir, os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
return 0, err
}
n, err := file.Write(buffer.Bytes())
if err != nil {
return 0, err
}
return n, nil
}
This is the execution of the function, together with the standard json.Marshal() or json.MarshalIndent() which overwrites the file
这是函数的执行,以及覆盖文件的标准 json.Marshal() 或 json.MarshalIndent()
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
minerals "./minerals"
srf "./srf"
)
func main() {
//array of Test struct
var SomeType [10]minerals.Test
//Create 10 units of some random data to write
for a := 0; a < 10; a++ {
SomeType[a] = minerals.Test{
Name: "Rand",
Id: 123,
A: "desc",
Num: 999,
Link: "somelink",
People: []string{"John Doe", "Aby Daby"},
}
}
//writes aditional data to existing file, or creates a new file
n, err := srf.WriteDataToFileAsJSON(SomeType, "test2.json")
if err != nil {
log.Fatal(err)
}
fmt.Println("srf printed ", n, " bytes to ", "test2.json")
//overrides previous file
b, _ := json.MarshalIndent(SomeType, "", "\t")
ioutil.WriteFile("test.json", b, 0644)
}
Why is this useful?
File.Write()returns bytes written to the file! So this is perfect if you want to manage memory or storage.
为什么这很有用?
File.Write()返回写入文件的字节!所以如果你想管理内存或存储,这是完美的。
WriteDataToFileAsJSON() (numberOfBytesWritten, error)

