简体   繁体   English

多个 map[string] 接口并将它们映射到多个 json 文件 GOLANG

[英]Multiple map[string]interface and and mapping them to multiple json files GOLANG

How can i create and array of maps[string]interface to add multiple json files (not all json in one, but in different).如何创建地图数组和数组[字符串] 接口以添加多个 json 文件(不是所有 json 合而为一,而是不同)。 I created a code, that add all json files in one.我创建了一个代码,将所有 json 文件添加到一个文件中。 But in the future i need to compare field in map[string]interface.但将来我需要比较 map[string]interface 中的字段。 I think that need to create a loop.我认为需要创建一个循环。 Here my program code:这是我的程序代码:

var master map[string]interface{}

func main() {
    fileIndex := 3 // three json files. All named test1.json, test2.json and test3.json
    for i := 1; i <= fileIndex; i++ {
        fileName := fmt.Sprintf("%s%d%s", "test", i, ".json")
        // Open jsonFile
        jsonFile, err := os.Open(fileName)
        if err != nil {
            log.Println("Error:", err)
        }

        defer jsonFile.Close()

        byteValue, _ := ioutil.ReadAll(jsonFile)

        json.Unmarshal(byteValue, &master)

        fmt.Println(master)

    }
}

And here my 3 json: First:这里是我的 3 json: 首先:

 {
     "name":"Kate",
     "date":"2013-04-23T19:24:59.511Z",
     "data":"is nice"
 }

Second:第二:

{
    "name":"Gleison",
    "date":"2012-04-23T19:25:00.511Z",
    "data":"is a good person"
}

Third:第三:

{
    "name":"Rodrigo",
    "date":"2013-04-23T20:24:59.511Z",
    "data":"is kind"
}

It is necessary to divide them into different map[string]interface.有必要将它们分成不同的map[string]接口。 Without creating struct.无需创建结构。

For an array, I think you are looking []map[string]interface{}.对于数组,我认为您正在寻找 []map[string]interface{}。 You can simply create this variable and append it if I understood your question correctly如果我正确理解你的问题,你可以简单地创建这个变量和 append

Here is a modified example这是一个修改过的例子

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "os"
)

func main() {

    var master map[string]interface{}
    var allMaster []map[string]interface{}

    fileIndex := 3 // three json files. All named test1.json, test2.json and test3.json
    for i := 1; i <= fileIndex; i++ {
        fileName := fmt.Sprintf("%s%d%s", "test", i, ".json")
        // Open jsonFile
        jsonFile, err := os.Open(fileName)
        if err != nil {
            log.Println("Error:", err)
        }

        defer jsonFile.Close()

        byteValue, _ := ioutil.ReadAll(jsonFile)

        err = json.Unmarshal(byteValue, &master)
        if err != nil {
            log.Fatal(err)
        }

        allMaster = append(allMaster, master)
        fmt.Println(allMaster)

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM