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

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

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;

  1. [
  2. { title: 'JavaScript: The Good Parts', author: 'Douglas Crockford',
  3. releaseDate: '2008', keywords: 'JavaScript Programming' },
  4. { title: 'The Little Book on CoffeeScript', author: 'Alex MacCaw',
  5. releaseDate: '2012', keywords: 'CoffeeScript Programming' },
  6. { title: 'Scala for the Impatient', author: 'Cay S. Horstmann',
  7. releaseDate: '2012', keywords: 'Scala Programming' },
  8. { title: 'American Psycho', author: 'Bret Easton Ellis',
  9. releaseDate: '1991', keywords: 'Novel Splatter' },
  10. { title: 'Eloquent JavaScript', author: 'Marijn Haverbeke',
  11. releaseDate: '2011', keywords: 'JavaScript Programming' }
  12. ]

or a single one like;

  1. { title: 'Eloquent JavaScript', author: 'Marijn Haverbeke',
  2. 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"] }

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

  1. for i := 0; i < len(b); i++ {
  2. fmt.Printf("%s by %s was release at %s\n", b[i]["title"], b[i]["author"])
  3. switch v := b[i]["keywords"].(type) {
  4. case []interface{}:
  5. for i := 0; i < len(v); i++ {
  6. switch v := v[i].(type) {
  7. case string:
  8. fmt.Println("\tstring in a slice", v)
  9. case float64: //numbers in json are float64 by default
  10. fmt.Println("\tnumber in a slice", v)
  11. default:
  12. fmt.Printf("\tunknown type (%T)", v, v)
  13. }
  14. }
  15. case string:
  16. fmt.Println("\tstring", v)
  17. }
  18. }

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 :

  1. for i := 0; i &lt; len(b); i++ {
  2. fmt.Printf(&quot;%s by %s was release at %s\n&quot;, b[i][&quot;title&quot;], b[i][&quot;author&quot;])
  3. switch v := b[i][&quot;keywords&quot;].(type) {
  4. case []interface{}:
  5. for i := 0; i &lt; len(v); i++ {
  6. switch v := v[i].(type) {
  7. case string:
  8. fmt.Println(&quot;\tstring in a slice&quot;, v)
  9. case float64: //numbers in json are float64 by default
  10. fmt.Println(&quot;\tnumber in a slice&quot;, v)
  11. default:
  12. fmt.Printf(&quot;\tunknown type (%T)&quot;, v, v)
  13. }
  14. }
  15. case string:
  16. fmt.Println(&quot;\tstring&quot;, v)
  17. }
  18. }

<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:

确定