如何将 JSON 转换为 CSV?

2024-03-14

我该如何修复该错误?

http://play.golang.org/p/0UMnUZOUHw http://play.golang.org/p/0UMnUZOUHw

// JSON to CSV in Golang
package main

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

type Json struct {
    RecordID int64  `json:"recordId"`
    DOJ      string `json:"Date of joining"`
    EmpID    string `json:"Employee ID"`
}

func main() {
    // reading data from JSON File
    data, err := ioutil.ReadFile("./people.json")
    if err != nil {
        fmt.Println(err)
    }
    // Unmarshal JSON data
    var d []Json
    err = json.Unmarshal([]byte(data), &d)
    if err != nil {
        fmt.Println(err)
    }
    // Create a csv file
    f, _ := os.Create("./people.csv")
    defer f.Close()
    // Write Unmarshaled json data to CSV file
    w := csv.NewWriter(f)

    // How to proceed further?
    /* I am getting errors if i use below
    for _,obj := range d {
      var record []interface{}
      record = append(record, obj.RecordID)
      record = append(record, obj.DOJ)
      record = append(record, obj.EmpID)
      w.Write(record)
    }
    */
}

Error:

cannot use record (type []interface {}) as type []string in function argument

例如,

package main

import (
    "encoding/csv"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
    "strconv"
)

type Json struct {
    RecordID int64  `json:"recordId"`
    DOJ      string `json:"Date of joining"`
    EmpID    string `json:"Employee ID"`
}

func main() {
    // reading data from JSON File
    data, err := ioutil.ReadFile("./people.json")
    if err != nil {
        fmt.Println(err)
    }
    // Unmarshal JSON data
    var d []Json
    err = json.Unmarshal([]byte(data), &d)
    if err != nil {
        fmt.Println(err)
    }
    // Create a csv file
    f, err := os.Create("./people.csv")
    if err != nil {
        fmt.Println(err)
    }
    defer f.Close()
    // Write Unmarshaled json data to CSV file
    w := csv.NewWriter(f)
    for _, obj := range d {
        var record []string
        record = append(record, strconv.FormatInt(obj.RecordID, 10))
        record = append(record, obj.DOJ)
        record = append(record, obj.EmpID)
        w.Write(record)
    }
    w.Flush()
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 JSON 转换为 CSV? 的相关文章

  • 空或不需要的结构字段

    我有两个结构体 代表将插入到 mongodb 数据库中的模型 一个结构 投资 将另一个结构 集团 作为其字段之一 type Group struct Base Name string json name bson name type Inv
  • 在 Go 中将 float 转换为 int 时如何舍入到最近的 int

    将 float 转换为 int 时 小数点将被丢弃 有什么干净的方法可以将其四舍五入到最接近的整数 x int 3 6 应等于 4 而不是 3 int f 0 5 如果 gt 5 将导致向上舍入
  • 如何分发仅二进制的 go 包

    我想以二进制形式分发包而不包含源代码 我的演示项目目录结构是这样的 demo greet greet go hi hi go hello hello go main go main go package main import fmt de
  • 使用 Golang 通道处理 HTTP 请求

    我正在尝试构建一个简单的 Golang Appengine 应用程序 它使用通道来处理每个 http 请求 原因是我希望每个请求执行合理的大型内存计算 并且每个请求都以线程安全的方式执行 即来自并发请求的计算不会混合 这一点很重要 本质上
  • formatFloat :将浮点数转换为字符串[重复]

    这个问题在这里已经有答案了 http golang org pkg strconv http golang org pkg strconv http play golang org p 4VNRgW8WoB http play golang
  • 带 cookie 身份验证的 Gorilla websocket

    这是我的设置 我正在构建一个带有用户登录的服务 使用 Negroni 和 Gorilla 登录后 用户会获得一个会话 cookie 服务器使用该会话 cookie 来授权受保护的端点 受保护的端点之一允许用户 客户端与服务器打开 Webso
  • 为什么结构体不能转换为嵌入类型

    package main type Inner struct x int type Outer struct Inner func main x Inner 1 y Outer x cannot convert x type Inner t
  • 使用 MongoDB Atlas 时 mongo-go-driver 因服务器选择超时而失败

    去版本 1 12 5 我有这个使用 node js mongo 驱动程序的代码 const MongoClient require mongodb MongoClient const uri process env MONGO HOST d
  • Golang 优雅地关闭 HTTP 服务器并进行错误处理

    我正在让我的 HTTP 服务器正常关闭 我从帖子中获取了提示here https stackoverflow com questions 39320025 how to stop http listenandserve 并且到目前为止已经像
  • 在 Go 中生成随机、固定长度的字节数组

    我有一个字节数组 固定长度为4 token make byte 4 我需要将每个字节设置为随机字节 我怎样才能以最有效的方式做到这一点 这math rand就我而言 方法不提供随机字节函数 也许有一种内置的方法 或者我应该生成一个随机字符串
  • exec git 命令拒绝重定向到 Go 中的文件

    我试图从 go 调用 git log 并将输出重定向到给定文件 cmdArgs string log numstat reverse fmt Sprintf s HEAD 89c98f5ec48c8ac383ea9e27d792c3dc77
  • Go中如何从json字符串中获取键值

    我想尝试从 Go 中的 JSON 获取键值 但我不确定如何操作 我已经能够使用 simplejson 读取 json 值 但是我无法找到如何获取键值 有人能指出我正确的方向和 或帮助我吗 谢谢你 您可以通过执行以下操作来获取 JSON 结构
  • 检查值是否实现接口的说明

    我读过 Effective Go 和其他类似这样的问答 golang接口合规性编译类型检查 https stackoverflow com questions 17994519 golang interface compliance com
  • Go中如何自定义http.Client或http.Transport超时重试?

    我想实现一个自定义http Transport对于标准http Client 如果客户端超时 它将自动重试 附 由于某种原因 习俗http Transport is a 一定有 我已经查过了hashcorp go retryablehttp
  • 构建链代码时 ltdl.h 未找到错误

    我正在尝试使用构建链码go build 当我运行 Go build 命令时它的报告 hyperledger fabric vendor github com miekg pkcs11 pkcs11 g o 29 18 fatal error
  • 在 Go 中跟踪 HTTP 请求时指定超时

    我知道通过执行以下操作来指定 HTTP 请求超时的常用方法 httpClient http Client Timeout time Duration 5 time Second 但是 我似乎不知道在跟踪 HTTP 请求时如何执行相同的操作
  • 如何解析 Content-Disposition 标头以检索文件名属性?

    使用 go 如何解析从 http HEAD 请求检索到的 Content Disposition 标头以获取文件的文件名 此外 如何从 http HEAD 响应中检索标头本身 这样的事情正确吗 resp err http Head http
  • 如何在 Go 应用程序中处理打开/关闭数据库连接?

    我的 Web API 应用程序中有一组函数 他们对 Postgres 数据库中的数据执行一些操作 func CreateUser db err sql Open postgres user postgres password passwor
  • 鸭子在 Go 中打字

    我想写一个Join函数接受任意对象String 方法 package main import fmt strings type myint int func i myint String string return fmt Sprintf
  • 如何在 Go 中将环境变量传递给测试用例

    在为 Go 编写测试用例时 传递需要提供给测试的环境变量的标准方法是什么 例如 我们不想在测试用例的源代码中嵌入密码 处理这个问题最标准的方法是什么 我们让测试用例寻找配置文件吗 还有别的事吗 看来我偶然发现了答案 将其添加到测试用例中可以

随机推荐