Golang:如何解析同时包含特征和数据的 JSON?

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

Golang: how to parse json that get trait and data both?

问题

我得到了一个包含字典数据的变量,格式如下:{{"单词名称":"单词含义"},{"单词名称":"单词含义"},...}
我想将其解析为一个单词的映射表。我尝试使用interface{}编写代码,但是我无法想象如何实现。谢谢阅读。

英文:

I got a dic data with {{"word name":"word meaning"},{"word name":"word meaning"},…}
I want to parse to map of the words.
I tried to write code with interface{} but i cant imagine how to. Thanks for reading.

答案1

得分: 2

如果你有一种方法可以将第一个和最后一个花括号改为方括号,那么你可以按照以下方式进行操作:

package main

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

func main() {

    var raw_list []map[string]string

    var jsonText = []byte(`[
        {"Cat": "small animal"},
        {"Cow": "Big animal"}
        ]`)

    err := json.Unmarshal(jsonText, &raw_list)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("raw_list : %s\n", raw_list)

    new_map := make(map[string]string)

    for _, ele := range raw_list {
        for key, val := range ele {
            new_map[key] = val
        }
    }

    fmt.Printf("new_map %s\n", new_map)
}

GoPlayground

结果:

raw_list : [map[Cat:small animal] map[Cow:Big animal]]
new_map map[Cat:small animal Cow:Big animal]
英文:

If you have a way of changing first and last curly brace, to a square brackets, then you could do the following:

package main

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

func main() {

	var raw_list []map[string]string
	
	var jsonText = []byte(`[
        {"Cat": "small animal"},
        {"Cow": "Big animal"}
        ]`)

	err := json.Unmarshal(jsonText, &raw_list)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("raw_list : %s\n", raw_list)

	new_map := make(map[string]string)

	for _, ele := range raw_list {
		for key, val := range ele {
			new_map[key] = val
		}
	}

	fmt.Printf("new_map %s\n", new_map)
}

GoPlayground

Result:

raw_list : [map[Cat:small animal] map[Cow:Big animal]]
new_map map[Cat:small animal Cow:Big animal]

答案2

得分: 1

例如:

package main

import (
    "encoding/json"
    "fmt"
)

var jsonText = []byte(`[
    {"Name": "Cat", "Meaning": "一只猫"},
    {"Name": "Dog", "Meaning": "一只狗"}
]`)

type Word struct {
    Name, Meaning string
}

func main() {
    var words []Word
    dict := make(map[string]string)
    if err := json.Unmarshal(jsonText, &words); err != nil {
        fmt.Println("错误:", err)
    }
    for _, w := range words {
        dict[w.Name] = w.Meaning
    }
    fmt.Printf("%v", dict)
}

输出结果:

map[Cat:一只猫 Dog:一只狗]

Playground

英文:

For example:

package main

import (
	"encoding/json"
	"fmt"
)

var jsonText = []byte(`[
	{"Name": "Cat", "Meaning": "A Cat"},
	{"Name": "Dog", "Meaning": "A Dog"}
]`)

type Word struct {
	Name, Meaning string
}

func main() {
	var words []Word
	dict := make(map[string]string)
	if err := json.Unmarshal(jsonText, &words); err != nil {
		fmt.Println("error:", err)
	}
	for _, w := range words {
		dict[w.Name] = w.Meaning
	}
	fmt.Printf("%v", dict)
}

Produces:

> map[Cat:A Cat Dog:A Dog]

Playground

答案3

得分: 0

你的JSON应该像下面这样:

{
    "word 1": "meaning 1",
    "word 2": "meaning 2"
}

为了实现这个,你可以使用类似下面这样的代码:

func fixJson(s string) string {
    s = strings.Replace(s, "{", "", -1)
    s = strings.Replace(s, "}", "", -1)
    return "{" + s + "}"
}

完整的代码如下:

package main

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

func fixJson(s string) string {
    s = strings.Replace(s, "{", "", -1)
    s = strings.Replace(s, "}", "", -1)
    return "{" + s + "}"
}

func main() {

    var words map[string]string

    var text = `{
        {"word 1": "meaning 1"},
        {"word 2": "meaning 2"}
    }`

    var jsonText = []byte(fixJson(text))

    err := json.Unmarshal(jsonText, &words)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(words)
}

Playground

英文:

Your JSON should be like the following

{
    "word 1": "meaning 1",
    "word 2": "meaning 2"
}

to accomplish that you may use something like that

func fixJson(s string) string {
    s = strings.Replace(s, "{", "", -1)
    s = strings.Replace(s, "}", "", -1)
    return "{" + s + "}"
}

Full code

package main

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

func fixJson(s string) string {
    s = strings.Replace(s, "{", "", -1)
    s = strings.Replace(s, "}", "", -1)
    return "{" + s + "}"
}

func main() {

    var words map[string]string

    var text = `{
        {"word 1": "meaning 1"},
        {"word 2": "meaning 2"}
    }`

    var jsonText = []byte(fixJson(text))

    err := json.Unmarshal(jsonText, &words)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(words)
}

Playground

huangapple
  • 本文由 发表于 2015年2月1日 09:20:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/28258456.html
匿名

发表评论

匿名网友

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

确定