在同一文件中添加两个json文件

时间:2020-06-13 17:24:42

标签: json go

我有此版本的代码:我需要它来更改部分代码或只是帮助我,因为我检查了google中的所有链接。

[{"data":"is nice",
  "date":"2012-04-23T18:24:59.511Z",
  "name":"Kate"},
 {"data":"is a good person",
  "date":"2012-04-23T18:25:00.511Z",
  "name":"Gleison"}]

}

最后我得到了:

{
    "name":["kate","gleison"],
    "date":"2012-04-23T18:00:00.000Z",
    "data":["is nice","is a good person"]
}

但是我想要得到什么:

 {
        "name":"Kate",
        "date":"2012-04-23T18:24:59.511Z",
        "data":"is nice"
    },
 {
    "name":"Gleison",
    "date":"2012-04-23T18:25:00.511Z",
    "data":"is a good person"
}

您能帮我更改代码的某些部分以对其进行修复吗?

我的2个json文件:

{{1}}

1 个答案:

答案 0 :(得分:0)

migrations, migrations1 := make(map[string]interface{}), make(map[string]interface{})

data := `{ "name":"Kate", "date":"2012-04-23T18:24:59.511Z", "data":"is nice" }`
data1 := `{ "name":"Gleison", "date":"2012-04-23T18:25:00.511Z", "data":"is a good person" }`

err := json.Unmarshal([]byte(data), &migrations)
if err != nil {
    panic(err)
}

err = json.Unmarshal([]byte(data1), &migrations1)
if err != nil {
    panic(err)
}

layout := "2006-01-02T15:04:05.000Z"

t, err := time.Parse(layout, fmt.Sprint(migrations["date"]))
t1, err := time.Parse(layout, fmt.Sprint(migrations1["date"]))
if err != nil {
    fmt.Println(err)
}

firsthour := t.Hour()
secondhour := t1.Hour()

if firsthour == secondhour {
    result := make(map[string][]interface{})

    for k, v := range migrations {
        result[k] = append(result[k], v)
    }

    for k, v := range migrations1 {
        result[k] = append(result[k], v)
    }

    fmt.Println(result)

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

    os.Stdout.Write(b)

} else {
    err = json.Unmarshal([]byte(data), &migrations)
    if err != nil {
        panic(err)
    }

    err = json.Unmarshal([]byte(data1), &migrations1)
    if err != nil {
        panic(err)
    }

    fmt.Println(migrations, migrations)
}