duanbi6522 2014-08-29 10:26
浏览 383
已采纳

使用Go正确解析JSON数据时出错

I'm a newbie to Go and trying use a library from github to parse JSON to CSV. https://github.com/jehiah/json2csv

But i encountered this issue: https://github.com/jehiah/json2csv/issues/22 to which the author is not replying.

I realized that if we give following JSON as json.input to the file:

{"user": {"name":["jehiah, mike, semo"], "password": "root"}, "remote_ip": "127.0.0.1", "dt" : "[20/Aug/2010:01:12:44 -0400]"}
{"user": {"name":["jeroenjanssens", "jeroen2", "jero55"], "password": "123"}, "remote_ip": "192.168.0.1", "dt" : "[20/Aug/2010:01:12:44 -0400]"}
{"user": {"name":"markdata", "password": ""}, "remote_ip": "76.216.210.0", "dt" : "[20/Aug/2010:01:12:45 -0400]"}

Now if i try using it as command: go run main.go -k user.name -i input.json -o output.json

it returns following output:

"[jehiah, mike, semo]"
[jeroenjanssens jeroen2 jero55]
markdata

but as described in opend issued, i'm expecting the response as:

jehiah, mike, semo
jeroenjanssens, jeroen2, jero55
markdata

i'm guessing it is happening due to line: https://github.com/jehiah/json2csv/blob/master/main.go#L110 which is anyhow removing commas while reading the line.

Can you please advice to how to achieve above desired output?

Regards

  • 写回答

2条回答 默认 最新

  • dongxiatuo9827 2014-08-29 11:15
    关注

    Using this code you will be able to read your json data in a Go struct really easily:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    // define the User type 
    type User struct {
        Name     []string
        Password string
    }
    
    type DataStruct struct {
        User      User
        Remote_ip string
        Dt        string
    }
    
    func main() {
         var jsonBlob = []byte(`{"user": {"name":["jehiah, mike, semo"], "password": "root"},
      "remote_ip": "127.0.0.1", "dt" : "[20/Aug/2010:01:12:44 -0400]"}`)
    
         var data DataStruct
         err := json.Unmarshal(jsonBlob, &data)
         if err != nil {
              fmt.Println("error:", err)
         } else {
              fmt.Printf("%+v", data)
         }
    
    }
    

    If you have never used the encoding/json package you should read the official Golang json article.

    When you have correctly read the data in the DataStruct structure, you will be able to serialize it using the proper Golang csv package.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名