2017-07-08 95 views
2

我怎麼會從下面JSON解析嵌套的JSON在去語言

這裏分析和提取某些值是樣本JSON響應

{"success":true,"endpoint":"https://api.abcxyz.com","info": 
{"Guestconnected":134,"Guestratio":100000.06963,"symbol1": 
{"code":"NY","symbol":"*","name":"newyear","codev":391.78161,"symbolAppearsAfter 
":false,"local":true},"symbol2": 
{"code":"HNY","symbol":"@","name":"HappyNewYear","codev":1000000.0960,"symbolApp 
earsAfter":true,"local":false},"latest": 
{"value":1597509,"autovalue":"00099cf8da58a36c08f2ef98650ff6043ddfb","height":47 
4696,"time":1499527696}},"Allguest": 
{"all":4,"filtered":4,"total_invitations":15430,"sent_invitations":15430,"final_ 
invitations":0},"Guestlist": 
[{"GuestCode":"369AR","all":2,"total_invitations":5430,"sent_invitations":5430," 
final_invitations":0,"change":0,"accounts":0}, 
{"GuestCode":"6POIA96TY","all":2,"total_invitations":10000,"sent_invitations":10 
000,"final_invitations":0,"change":0,"accounts":0}]} 

我的代碼是:

package main 

import (
    "encoding/json" 
    "fmt" 
    "log" 
    "net/http" 
) 


type object struct { 
    Success bool `json:"success"` 
    Endpoint string `json:"endpoint"` 
    Allguest struct { 
     All int `json:"all"` 
     Filtered int `json:"filtered"` 
     TotalInvitations int `json:"total_invitations"` 
     SentInvitations int `json:"sent_invitations"` 
     FinalInvitations int `json:"final_invitations"` 
    } `json:"Allguest"` 
    Guestlist []struct { 
     GuestCode string `json:"GuestCode"` 
     All int `json:"all"` 
     TotalInvitations int `json:"total_invitations"` 
     SentInvitations int `json:"sent_invitations"` 
     FinalInvitations int `json:"final_invitations"` 
     Change int `json:"change"` 
     Accounts int `json:"accounts"` 
    } `json:"Guestlist"` 
} 

func main() { 

uri := "https://siteurl.com/api?lists=1" 
res, err := http.Get(uri) 
fmt.Println(uri) 
if err != nil { 
fmt.Println("Error:", err) 
    log.Fatal(err) 
} 
defer res.Body.Close() 

var s object 
err := json.NewDecoder(res.Body).Decode(&s) 
if err != nil { 
    log.Fatal(err) 
    fmt.Println("Error:", err) 
} 
fmt.Println(s.Success) 
fmt.Println(s.Allguest.TotalInvitations) 
for i := 0; i < 6; i++ { 
fmt.Println(s.Guestlist[i].TotalInvitations) 
) 

} 

問題是:

  1. 如果回覆爲空,則表明index out of range error我們該如何避免?

  2. 應用條件,如果TotalInvitations值大於100然後在100.csv其他保存保存others.csv

回答

1

使用gjson PKG從JSON文件中獲取價值的簡單方法

例如:

package main 

import (
    "fmt" 

    "github.com/tidwall/gjson" 
) 

func main() { 
    data := []byte(`{ 
    "success": true, 
    "endpoint": "https://api.abcxyz.com", 
    "info": { 
     "Guestconnected": 134, 
     "Guestratio": 100000.06963, 
     "symbol1": { 
     "code": "NY", 
     "symbol": "*", 
     "name": "newyear", 
     "codev": 391.78161, 
     "symbolAppearsAfter": false, 
     "local": true 
     }, 
     "symbol2": { 
     "code": "HNY", 
     "symbol": "@", 
     "name": "HappyNewYear", 
     "codev": 1000000.096, 
     "symbolAppearsAfter": true, 
     "local": false 
     }, 
     "latest": { 
     "value": 1597509, 
     "autovalue": "00099cf8da58a36c08f2ef98650ff6043ddfb", 
     "height": 474696, 
     "time": 1499527696 
     } 
    }, 
    "Allguest": { 
     "all": 4, 
     "filtered": 4, 
     "total_invitations": 15430, 
     "sent_invitations": 15430, 
     "final_invitations": 0 
    }, 
    "Guestlist": [ 
     { 
     "GuestCode": "369AR", 
     "all": 2, 
     "total_invitations": 5430, 
     "sent_invitations": 5430, 
     "final_invitations": 0, 
     "change": 0, 
     "accounts": 0 
     }, 
     { 
     "GuestCode": "6POIA96TY", 
     "all": 2, 
     "total_invitations": 10000, 
     "sent_invitations": 10000, 
     "final_invitations": 0, 
     "change": 0, 
     "accounts": 0 
     } 
    ] 
    } 
    `) 

    r := gjson.GetBytes(data, "Allguest.total_invitations") 
    fmt.Println(r.Value()) // output 15430 

    r = gjson.GetBytes(data, "Guestlist.#.total_invitations") 
    fmt.Println(r.Value()) // output [5430 10000] 
} 
0
  1. 如果響應爲空,它會給出索引超出範圍錯誤我們如何避免 ?

    除非我誤解了你,否則應答無效。如果您收到2個Guestlist項目,則只能循環訪問這2個,這意味着for i := 0; i < 6; i++錯誤。將其更改爲for i := 0; i < len(s.Guestlist); i++for i := range s.Guestlist

  2. 應用條件,如果TotalInvitations值大於100,然後 保存在100.csv其他保存在others.csv

    你可能會希望os包的Create功能來創建一個新的文件寫入或OpenFile函數,O_CREATE, O_WRONLY, and O_APPEND文件打開標誌,並且您可以通過0755作爲權限模式(或另一組八進制權限,如果要更改文件的訪問權限)。

    然後,您可以使用csvWriter := csv.NewWriter(csvFile)來包裝得到的io.Writer(假設打開文件沒有錯誤)。從那裏,您可以將所需的任何信息作爲CSV記錄寫入文件。不要忘記調用csvWriter.Flush來刷新輸出緩衝區和csvWriter.Error以檢查是否有刷新輸出緩衝區的錯誤。另外不要忘記關閉你打開的文件。

+0

@Nancyme您應該考慮查看[文檔的學習部分](https:// golang。org/doc /#learning)以及[探索核心軟件包](https://golang.org/pkg/)。你似乎不明白'* csv.Writer'的'Write'方法只接受'[] string',而不是'int'。您有正確的想法,但您需要確定要寫入文件的數據以及如何將該數據轉換爲一段字符串才能完成此操作。 –

+0

像這樣'TotalInvites:= [] [] string {{s.Guestlist [i] .TotalInvitations}} – Nancyme

+0

@Nancyme您不會將整數轉換爲'[] [] string'對象;你正在用一個整數作爲唯一的值創建一個新的[[] []字符串對象,這將不起作用,因爲'int'不是與'string'兼容的類型。學習,不要只是猜測。如果您遇到麻煩並且需要提出問題,我們會在這裏提供幫助,而不是教您使用整個語言;我在這個答案的最後評論中鏈接了學習資源。 –

0

如果你只需要你可以從JSON定義,只有這些領域你有興趣,而且如果值可以爲null最好是在結構聲明指針的結構某些條目。請看看操場上的示例:https://play.golang.org/p/mEwSXvPg3D