How to use golang to convert a multi-line json to one-line json?

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

How to use golang to convert a multi-line json to one-line json?

问题

你可以使用Go语言将多行的JSON转换为单行的JSON。以下是一个示例代码:

package main

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

func main() {
	// 多行的JSON字符串
	multiLineJSON := `{
		"release_date": "2004-11-09",
		"status": "retired",
		"engine": "Gecko",
		"engine_version": "1.7"
	}`

	// 移除换行符和空格
	oneLineJSON := strings.ReplaceAll(multiLineJSON, "\n", "")
	oneLineJSON = strings.ReplaceAll(oneLineJSON, " ", "")

	// 输出单行的JSON字符串
	fmt.Println(oneLineJSON)

	// 将单行的JSON字符串解析为JSON对象
	var data map[string]interface{}
	err := json.Unmarshal([]byte(oneLineJSON), &data)
	if err != nil {
		fmt.Println("解析JSON失败:", err)
		return
	}

	// 输出解析后的JSON对象
	fmt.Println(data)
}

运行以上代码,你将得到以下输出:

{"release_date":"2004-11-09","status":"retired","engine":"Gecko","engine_version":"1.7"}
map[engine:Gecko engine_version:1.7 release_date:2004-11-09 status:retired]

其中,oneLineJSON变量存储了转换后的单行JSON字符串。你可以根据需要对其进行进一步处理或解析为JSON对象。

英文:

How can I convert a multi-line json to a one-line json using Go?

From:

{
          "release_date": "2004-11-09",
          "status": "retired",
          "engine": "Gecko",
          "engine_version": "1.7"
        }

To:

{"release_date":"2004-11-09","status":"retired","engine":"Gecko","engine_version":"1.7"}

答案1

得分: 9

json.Compact() 正是这样做的:

> func Compact(dst *bytes.Buffer, src []byte) error
> Compact 函数将 src 的 JSON 编码附加到 dst 中,忽略无关的空格字符。

json.Compact() 优于先解组再重新组合,因为它适用于任何有效的 JSON,并且速度非常快(它不会创建和丢弃 Go 值)。它也优于使用任何正则表达式,同样,它的速度非常快,而且正则表达式无法完全理解 JSON 语法,因此可能导致数据丢失。

例如:

func main() {
	dst := &bytes.Buffer{}
	if err := json.Compact(dst, []byte(src)); err != nil {
		panic(err)
	}
	fmt.Println(dst.String())
}

const src = `{
          "release_date": "2004-11-09",
          "status": "retired",
          "engine": "Gecko",
          "engine_version": "1.7"
        }`

这将输出(在 Go Playground 上尝试一下):

{"release_date":"2004-11-09","status":"retired","engine":"Gecko","engine_version":"1.7"}
英文:

json.Compact() does exactly this:

> func Compact(dst *bytes.Buffer, src []byte) error
> Compact appends to dst the JSON-encoded src with insignificant space characters elided.

json.Compact() is superior to unmarshaling and marshaling again, as it works with any valid JSON, and is much-much faster (it doesn't create and throw away Go values). It's also superior to using any regexp, again, it's much-much faster and regexp does not understand JSON syntax fully, so it might result in data loss.

For example:

func main() {
	dst := &bytes.Buffer{}
	if err := json.Compact(dst, []byte(src)); err != nil {
		panic(err)
	}
	fmt.Println(dst.String())
}

const src = `{
          "release_date": "2004-11-09",
          "status": "retired",
          "engine": "Gecko",
          "engine_version": "1.7"
        }`

This will output (try it on the Go Playground):

{"release_date":"2004-11-09","status":"retired","engine":"Gecko","engine_version":"1.7"}

答案2

得分: 2

将多行JSON解组成一个struct(或者是一个map[string]any{}),然后将其编组为一个没有任何缩进选项的字符串。代码如下:

	v := struct {
		ReleaseDate string `json:"release_date"`
		Status      string `json:"status"`
		Engine      string `json:"engine"`
		Version     string `json:"engine_version"`
	}{}

	if err := json.Unmarshal([]byte(s), &v); err != nil {
		fmt.Printf("ERROR: %v\n", err)
	} else if bytes, err := json.Marshal(v); err != nil {
		fmt.Printf("ERROR: %v\n", err)
	} else {
		fmt.Printf("%v\n", string(bytes))
	}

Go Playground

英文:

Unmarshal the multi-line JSON into a struct (or alternatively a map[string]any{}) and then marshal it to a string without any indent options. So, something like this:

	v := struct {
		ReleaseDate string `json:"release_date"`
		Status      string `json:"status"`
		Engine      string `json:"engine"`
		Version     string `json:"engine_version"`
	}{}

	if err := json.Unmarshal([]byte(s), &v); err != nil {
		fmt.Printf("ERROR: %v\n", err)
	} else if bytes, err := json.Marshal(v); err != nil {
		fmt.Printf("ERROR: %v\n", err)
	} else {
		fmt.Printf("%v\n", string(bytes))
	}

(Go Playground)

答案3

得分: 0

如果你不知道将获得哪种类型的JSON,可以像这样使用:

package main

import (
	"encoding/json"
	"fmt"
)

const js = `
{
    "release_date": "2004-11-09",
    "status": "retired",
    "engine": "Gecko",
    "1": "1.7"
}

func main() {
	helper := make(map[string]interface{})

	err := json.Unmarshal([]byte(js), &helper)
	if err != nil {
		fmt.Printf("json.Unmarshal([]byte(s), &helper) failed. Error: %v\n", err)
		return
	}

	bytes, err := json.Marshal(helper)
	if err != nil {
		fmt.Printf("json.Marshal(helper) failed. Error: %v\n", err)
		return
	}

	fmt.Println(string(bytes))

}

在这里尝试:这里

不要使用替换空格,因为这可能会损坏JSON值。

英文:

If you dont know which kind of json you will get
just use like this

package main

import (
	"encoding/json"
	"fmt"
)

const js = `
{
    "release_date": "2004-11-09",
    "status": "retired",
    "engine": "Gecko",
    "1": "1.7"
}
`

func main() {
	helper := make(map[string]interface{})

	err := json.Unmarshal([]byte(js), &helper)
	if err != nil {
		fmt.Printf("json.Unmarshal([]byte(s), &helper) failed. Error:  %v\n", err)
        return
	} 
	
	bytes, err := json.Marshal(helper)
	if err != nil {
		fmt.Printf("json.Marshal(helper) failed. Error:  %v\n", err)
	    return
	}
	
	fmt.Println(string(bytes))
		
}

Try here

And don't use replacing spaces because you can damage json values

huangapple
  • 本文由 发表于 2022年6月14日 05:14:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/72609104.html
匿名

发表评论

匿名网友

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

确定