将JSON转换为Go中的map切片,以及将map切片转换为JSON,而不使用结构体。

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

Converting json to slice of maps and slice of maps to json in Go without using structs

问题

我正在尝试将来自HTTP请求的JSON字符串转换为映射切片。同时,我还需要将映射切片转换为JSON字符串,以便用于HTTP响应。

我想要在以下两种情况下将其转换为映射切片:

  1. 来自HTTP请求的JSON字符串可能是多个具有相同键值的JSON对象的数组,例如:

    [
    { "title": "JavaScript: The Good Parts", "author": "Douglas Crockford",
    "releaseDate": "2008", "keywords": "JavaScript Programming" },
    { "title": "The Little Book on CoffeeScript", "author": "Alex MacCaw",
    "releaseDate": "2012", "keywords": "CoffeeScript Programming" },
    { "title": "Scala for the Impatient", "author": "Cay S. Horstmann",
    "releaseDate": "2012", "keywords": "Scala Programming" },
    { "title": "American Psycho", "author": "Bret Easton Ellis",
    "releaseDate": "1991", "keywords": "Novel Splatter" },
    { "title": "Eloquent JavaScript", "author": "Marijn Haverbeke",
    "releaseDate": "2011", "keywords": "JavaScript Programming" }
    ]

  2. 或者可能是单个对象,例如:

    { "title": "Eloquent JavaScript", "author": "Marijn Haverbeke",
    "releaseDate": "2011", "keywords": "JavaScript Programming" }

第二个任务是将映射切片转换为JSON字符串。

然而,我在这两个过程中都没有成功。

我知道使用json包可以对结构体执行这两个任务。

由于设计上的考虑,我不应该预先编码结构体。

在Go语言中,是否有已知的方法可以实现这些功能?

英文:

I am trying to convert a json string from an http request to a slice of map/s.
And I should also convert a slice of map/s to json string to use for a http response.

I want to convert the followings into a slice of map/s, in both cases below.
The json string from the http request may be an array of several same key value json objects, like;

[
        { title: 'JavaScript: The Good Parts', author: 'Douglas Crockford',
          releaseDate: '2008', keywords: 'JavaScript Programming' },
        { title: 'The Little Book on CoffeeScript', author: 'Alex MacCaw',
          releaseDate: '2012', keywords: 'CoffeeScript Programming' },
        { title: 'Scala for the Impatient', author: 'Cay S. Horstmann',
          releaseDate: '2012', keywords: 'Scala Programming' },
        { title: 'American Psycho', author: 'Bret Easton Ellis',
          releaseDate: '1991', keywords: 'Novel Splatter' },
        { title: 'Eloquent JavaScript', author: 'Marijn Haverbeke',
          releaseDate: '2011', keywords: 'JavaScript Programming' }
]

or a single one like;

{ title: 'Eloquent JavaScript', author: 'Marijn Haverbeke',
  releaseDate: '2011', keywords: 'JavaScript Programming' }

And the second task is to convert a slice of map/s to a json string.

However, I could not mange to succeed in these two procedures.

json package makes it possible to do these two tasks for structs, I am aware of it.

I should not use structs coded beforehand, for a design concern.

Is there a known way to do these in Go.

答案1

得分: 2

你真的可以使用map[string]interface{},它可以很好地处理{ "title": ....., "keywords": ["CoffeeScript", "Programming"] }

你需要使用类似以下的代码:

for i := 0; i < len(b); i++ {
    fmt.Printf("%s by %s was release at %s\n", b[i]["title"], b[i]["author"])
    switch v := b[i]["keywords"].(type) {
    case []interface{}:
        for i := 0; i < len(v); i++ {
            switch v := v[i].(type) {
            case string:
                fmt.Println("\tstring in a slice", v)
            case float64: //numbers in json are float64 by default
                fmt.Println("\tnumber in a slice", v)
            default:
                fmt.Printf("\tunknown type (%T)", v, v)
            }
        }
    case string:
        fmt.Println("\tstring", v)
    }
}

playground

英文:

You really can use use map[string]interface{} and that would work with { &quot;title&quot;: ....., &quot;keywords&quot;: [&quot;CoffeeScript&quot;, &quot;Programming&quot;] } just fine

You'd have to use something like :

for i := 0; i &lt; len(b); i++ {
	fmt.Printf(&quot;%s by %s was release at %s\n&quot;, b[i][&quot;title&quot;], b[i][&quot;author&quot;])
	switch v := b[i][&quot;keywords&quot;].(type) {
	case []interface{}:
		for i := 0; i &lt; len(v); i++ {
			switch v := v[i].(type) {
			case string:
				fmt.Println(&quot;\tstring in a slice&quot;, v)
			case float64: //numbers in json are float64 by default
				fmt.Println(&quot;\tnumber in a slice&quot;, v)
			default:
				fmt.Printf(&quot;\tunknown type (%T)&quot;, v, v)
			}
		}
	case string:
		fmt.Println(&quot;\tstring&quot;, v)
	}
}

<kbd>playground</kbd>

答案2

得分: 1

你应该使用json.NewDecoder将JSON转换为映射切片,并使用json.NewEncoder将映射切片转换为JSON。

我在这里写了一个示例:http://play.golang.org/p/jbXYGC5pp2

请查看注释中的解释。

希望这对你有帮助。

英文:

you should use json.NewDecoder to convert JSON to slice of maps and json.NewEncoder to convert slice of maps into JSON.

i wrote it here http://play.golang.org/p/jbXYGC5pp2

see explanation in the comment.

i hope this help

huangapple
  • 本文由 发表于 2014年8月30日 22:14:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/25583281.html
匿名

发表评论

匿名网友

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

确定