Home > front end >  When the first stage is array, How to handle with go-simplejson
When the first stage is array, How to handle with go-simplejson

Time:01-12

JSON struct like below:

[
  {
    "sha": "eb08dc1940e073a5c40d8b53a5fd58760fde8f27",
    "node_id": "C_kwDOHb9FrtoAKGViMDhkYzE5NDBlMDczYTVjNDBkOGI1M2E1ZmQ1ODc2MGZkZThmMjc",
    "commit": {
      "author": {
        "name": "xxxx"
      },
      "committer": {
        "name": "xxxxx"
      },
      "message": "update DownLoad_Stitch_ACM.py",
      "tree": {
        "sha": "a30aab98319846f0e86da4a39ec05786e04c0a4f",
        "url": "xxxxx"
      },
      "url": "xxxxx",
      "comment_count": 0,
      "verification": {
        "verified": false,
        "reason": "unsigned",
        "signature": null,
        "payload": null
      }
    },
    "url": "xxxxx",
    "html_url": "xxxxx",
    "comments_url": "xxxxx",
    "author": {
      "login": "xxxxx",
      "id": "xxxxx",
      "node_id": "U_kgDOBkuicQ",
      "avatar_url": "https://avatars.githubusercontent.com/u/105620081?v=4",
      "gravatar_id": "",
      "type": "User",
      "site_admin": false
    },
    "committer": {
      "login": "xxxxx",
      "id": "xxxxx"
    },
    "parents": [
      {
        "sha": "cf867ec9dc4b904c466d9ad4b9338616d1213a06",
        "url": "xxxxx",
        "html_url": "xxxxx"
      }
    ]
  }
]

I don't know how to get the location 0's data.

content, _ := simplejson.NewJson(body)
arr, _ := content.Array()  // Here can get the all data, It's []interface{} type.

I cannot get the next data with arr[0]["sha"]. How to handle it?

CodePudding user response:

It is not clear to the compiler that arr is an array of map[string]interface{} at compile time, as arr[0] is of type interface{}. This basically means that the compiler knows nothing about this type, which is why you can't do a map lookup operation here.

You can add a type assertion to make sure you can use it as a map like this:

asMap := arr[0].(map[string]interface{})
fmt.Println(asMap["sha"])

To get the SHA as string, you can again add a type assertion behind it as well:

asString := asMap["sha"].(string)

This is also shown in this working example. The downside of this is that your program will panic in case the given data is not of the specified type. You could instead use a type assertion with a check if it worked (asString, ok := ...), but it gets cumbersome with more complex data.


This does work, but isn't really nice. I would recommend using a tool like this to generate Go structs and then use them in a type-safe way. First define a struct with all the info you need:

type ArrayElement struct {
    Sha string `json:"sha"`
    // Add more fields if you need them
}

Then you can just use the standard-library json package to unmarshal your data:

// This should have the same structure as the data you want to parse
var result []ArrayElement

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

fmt.Println(result[0].Sha)

Here is an example for that -- this is a more Go-like approach for converting JSON data.

CodePudding user response:

Your json data is wrong formatted. First of all, remove , after "id": "xxxxx", line:

    ...
    "id": "xxxxx"
    ...

You should check errors after NewJson to prevent find out if there is a problem:

    content, err := simplejson.NewJson(body)
    if err != nil {
        // log err
    }

For getting sha from first index, you simply can use simplejson built-in methods:

shaVal := content.GetIndex(0).Get("sha").String()
  •  Tags:  
  • go
  • Related