将数据追加到 JSON 中,并将其作为 map 在 GOLANG 中获取回来。

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

Appending data to json and getting it back as a map GOLANG

问题

我对JSON和GO都不太熟悉,但我可以帮你翻译代码部分。以下是翻译好的代码:

type DATA struct{
    Key string 
    Value string 
}

func writeToDB(key, value string) bool  {
    var jsonText = []byte(`[
        {"Key":"","Value":""}
    ]`)
    var indent []DATA
    err := json.Unmarshal([]byte(jsonText), &indent)
    if err != nil {
        fmt.Println(err)
    }
    indent = append(indent, DATA{Key:key, Value: value})

    result, error := json.MarshalIndent(indent, "", "   ")
    if error != nil {
        fmt.Println(error)
    }

    f, erro := os.OpenFile("db.json", os.O_APPEND|os.O_WRONLY, 0666)
    if erro != nil {
        fmt.Println(erro)
    }

    n, err := io.WriteString(f, string(result))
    if err != nil {
        fmt.Println(n, err)
    }
    return true
}

文件的输出结果将会是这样的:

[
   {
      "Key":"k1ey",
      "Value":"val1ue"
   },
   {
      "Key":"k133ey",
      "Value":"val1ue"
   }
]

但是你想要的格式是这样的:

{
   "key":"value",
   "key":"value",
   "key":"value"
}

我无法确保这段代码是否能达到你的要求,因为我对GO的JSON集成不太了解。希望这能帮到你。

英文:

I'm quite new to json and GO, I want to create a key and value based json file, which will append the data in key and value format, later will export it as a map(key and value), the data will save inside the db.json for later, to find the key value.
this is what I have:

type DATA struct{
	Key string 
	Value string 
}

func writeToDB(key, value string) bool  {


    var jsonText = []byte(`[
		Key:"", Value:""
    ]`)
    var indent []DATA
    err := json.Unmarshal([]byte(jsonText), &indent)
    if err != nil {
        fmt.Println(err)
    }
    indent = append(indent, DATA{Key:key, Value: value})


    result, error := json.Marshal(indent)
    if error != nil {
        fmt.Println(error)
    }

    f, erro := os.OpenFile("db.json", os.O_APPEND|os.O_WRONLY, 0666)
    if erro != nil {
        fmt.Println(erro)
    }

    n, err := io.WriteString(f, string(result))
    if err != nil {
        fmt.Println(n, err)
    }
	return true
}

the output of the file is like:

[{"Key":"k1ey","Value":"val1ue"}][{"Key":"k133ey","Value":"val1ue"}]

but I want something like:

{
   key:value
   key:value
   key:value
}

I can't get it right, I read many articles, but GO doesn't have an simple json integration

答案1

得分: 1

你需要将一个对象数组转换为映射(map),以下是一个基本示例:

func saveDbAsMap(db []DATA) {
    // 初始化一个字符串映射
    var dbAsMap = make(map[string]interface{})

    // 将对象数组转换为映射
    for i := 0; i < len(db); i++ {
        entry := db[i]
        dbAsMap[entry.Key] = entry.Value
    }

    // 将其转换为 JSON
    dbAsMapBytes, error := json.Marshal(dbAsMap)
    if error != nil {
        fmt.Println(error)
    }

    // 将其写入文件
    error = os.WriteFile("db.json", dbAsMapBytes, 0644)
    if error != nil {
        fmt.Println(error)
    }
}

用于测试的代码:

var db []DATA

func addToDB(key, value string) {
    db = append(db, DATA{Key: key, Value: value})
}

func main() {
    addToDB("key1", "value1")
    addToDB("key2", "value2")
    addToDB("key3", "value3")

    saveDbAsMap(db)
}

在 db.json 中的输出结果为:

{"key1":"value1","key2":"value2","key3":"value3"}
英文:

You need to convert an array of objects to a map, here is a basic example:

func saveDbAsMap(db []DATA) {
    // Initialize a string map
	var dbAsMap = make(map[string]interface{})

    // Convert array of objects to map
	for i := 0; i &lt; len(db); i++ {
		entry := db[i]
		dbAsMap[entry.Key] = entry.Value
	}

    // Marshal it to JSON
	dbAsMapBytes, error := json.Marshal(dbAsMap)
	if error != nil {
		fmt.Println(error)
	}

    // Write it to file
	error = os.WriteFile(&quot;db.json&quot;, dbAsMapBytes, 0644)
	if error != nil {
		fmt.Println(error)
	}
}

For testing:

var db []DATA

func addToDB(key, value string) {
	db = append(db, DATA{Key: key, Value: value})
}

func main() {
	addToDB(&quot;key1&quot;, &quot;value1&quot;)
	addToDB(&quot;key2&quot;, &quot;value2&quot;)
	addToDB(&quot;key3&quot;, &quot;value3&quot;)

	saveDbAsMap(db)
}

Output in db.json:

{&quot;key1&quot;:&quot;value1&quot;,&quot;key2&quot;:&quot;value2&quot;,&quot;key3&quot;:&quot;value3&quot;}

huangapple
  • 本文由 发表于 2022年10月15日 17:35:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/74078289.html
匿名

发表评论

匿名网友

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

确定