读取文件并在Go语言中将JSON文件放入嵌套结构中,并附加额外数据。

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

reading file and putting json file in Nested structure in Go lang with appending extra data

问题

我有一个嵌套结构,一个结构来自读取文件,另一个是我自己提供的,我需要将文件输出到标准输出。我已经有了代码,但是对于语法和逻辑我感到很困惑,因为我是Go语言的新手。(数据结构应该来自文件)

英文:

I have nested structure one structure coming from reading file and second I'm providing my self and I have to stdout the file. I got the code but I'm having hard time with syntax and logic I'm new to go lang.(the data structure supposed to come from the file)

答案1

得分: 1

程序读取文件,然后用其他内容替换数据。只需将数据放入输出的值中。

type Event struct {
    Specversion string    `json:"specversion"`
    ID          uuid.UUID `json:"id"` // uuid
    Source      string    `json:"source"`
    Type        string    `json:"type"`
    Time        time.Time `json:"time"`
    Data        string    `json:"data"` /* <= 更改为字符串 */
}

func main() {

    if len(os.Args) < 1 { // 检查是否提供了参数,如果第一个参数满足条件,则使用读取文件
        fmt.Println("Usage : " + os.Args[0] + " file name")
        help()
        os.Exit(1)
    }

    Data, err := ioutil.ReadFile(os.Args[1])
    if err != nil {
        fmt.Println("Cannot read the file or file does not exists")
        os.Exit(1)
    }

    e := Event{
        Specversion: "1.0",
        ID:          uuid.New(),
        Source:      "CSS",
        Type:        "", // 用户输入 -p 或 -u
        Time:        time.Now(),
        Data:        string(Data), /* <= 将数据放入输出值中 */
    }

    out, _ := json.MarshalIndent(e, "", "  ")
    fmt.Println(string(out))
}

在 playground 上运行以获取与问题中请求的结果

也许输出中的 \r\n 是问题所在。在编码结果之前,从 JSON 中删除回车符和换行符:

replacer := strings.NewReplacer("\r", "", "\n", "")
Data = []byte(replacer.Replace(string(Data)))

在 playground 上运行

如果你的意图是将 JSON 作为 JSON 包含,而不是将 JSON 引用为字符串,请使用 json.RawMessage

type Event struct {
    Specversion string    `json:"specversion"`
    ID          uuid.UUID `json:"id"` // uuid
    Source      string    `json:"source"`
    Type        string    `json:"type"`
    Time        time.Time `json:"time"`
    Data        json.RawMessage    `json:"data"` /* <= 更改为 json.RawMessage */
}

func main() {

    if len(os.Args) < 1 { // 检查是否提供了参数,如果第一个参数满足条件,则使用读取文件
        fmt.Println("Usage : " + os.Args[0] + " file name")
        help()
        os.Exit(1)
    }

    Data, err := ioutil.ReadFile(os.Args[1])
    if err != nil {
        fmt.Println("Cannot read the file or file does not exists")
        os.Exit(1)
    }

    e := Event{
        Specversion: "1.0",
        ID:          uuid.New(),
        Source:      "CSS",
        Type:        "", // 用户输入 -p 或 -u
        Time:        time.Now(),
        Data:        Data, /* <= 使用原始数据 */
    }

    out, _ := json.MarshalIndent(e, "", "  ")
    fmt.Println(string(out))
}

在 playground 上运行以查看嵌套的 JSON。你在问题中显示了一个带引号的字符串,但也许这个输出才是你真正想要的。

英文:

The program reads the file, but then substitutes something else in for data. Just put the data in the value marshaled to the output.

type Event struct {
	Specversion string    `json:&quot;specversion&quot;`
	ID          uuid.UUID `json:&quot;id&quot;` /// uuid
	Source      string    `json:&quot;source&quot;`
	Type        string    `json:&quot;type&quot;`
	Time        time.Time `json:&quot;time&quot;`
	Data        string    `json:&quot;data&quot;` /* &lt;= change to string */
}

func main() {

	if len(os.Args) &lt; 1 { //checking for provided argument if the first arg satisfy then use read file
		fmt.Println(&quot;Usage : &quot; + os.Args[0] + &quot; file name&quot;)
		help()
		os.Exit(1)
	}

	Data, err := ioutil.ReadFile(os.Args[1])
	if err != nil {
		fmt.Println(&quot;Cannot read the file or file does not exists&quot;)
		os.Exit(1)
	}

	e := Event{
		Specversion: &quot;1.0&quot;,
		ID:          uuid.New(),
		Source:      &quot;CSS&quot;,
		Type:        &quot;&quot;, //  user input -p or -u,
		Time:        time.Now(),
		Data:        string(Data), /* &lt;= stuff data into output value */
	}

	out, _ := json.MarshalIndent(e, &quot;&quot;, &quot;  &quot;)
	fmt.Println(string(out))
}

Run it on the playground to get results as requested in the question.

Perhaps the \r\n in the output are the problem. Remove carriage return and line feed from the JSON before encoding the result:

replacer := strings.NewReplacer(&quot;\r&quot;, &quot;&quot;, &quot;\n&quot;, &quot;&quot;)
Data = []byte(replacer.Replace(string(Data)))

Run it on the playground.

If you intent is to include the JSON as JSON instead of quoting the JSON as string, then use json.RawMessage:

type Event struct {
	Specversion string    `json:&quot;specversion&quot;`
	ID          uuid.UUID `json:&quot;id&quot;` /// uuid
	Source      string    `json:&quot;source&quot;`
	Type        string    `json:&quot;type&quot;`
	Time        time.Time `json:&quot;time&quot;`
	Data        json.RawMessage    `json:&quot;data&quot;` /* &lt;= change to json.RawMessage */
}

func main() {

	if len(os.Args) &lt; 1 { //checking for provided argument if the first arg satisfy then use read file
		fmt.Println(&quot;Usage : &quot; + os.Args[0] + &quot; file name&quot;)
		help()
		os.Exit(1)
	}

	Data, err := ioutil.ReadFile(os.Args[1])
	if err != nil {
		fmt.Println(&quot;Cannot read the file or file does not exists&quot;)
		os.Exit(1)
	}

	e := Event{
		Specversion: &quot;1.0&quot;,
		ID:          uuid.New(),
		Source:      &quot;CSS&quot;,
		Type:        &quot;&quot;, //  user input -p or -u,
		Time:        time.Now(),
		Data:        Data, /* &lt;== use data as is */
	}

	out, _ := json.MarshalIndent(e, &quot;&quot;, &quot;  &quot;)
	fmt.Println(string(out))
}

Run it on the playground to view nested json. You show a quoted string in the question, but perhaps this output is what you really want.

huangapple
  • 本文由 发表于 2022年9月9日 23:41:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/73664562.html
匿名

发表评论

匿名网友

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

确定