Home > database >  How to get data from big json in go
How to get data from big json in go

Time:11-16

I have that json and now i need to get that field "textValue": [ "BigFoot Inc." ]

All that I have now been able to get is data from an array of custom data. But I can't get data from a specific field. I tried to get the data, but everything is very sad, I will be glad for your help

JSON:

  "id": 759,
  "author": {
    "id": 1,
    "name": "Gogi Na Vole",
  "completedOn": "Never",
  "custom_fields": [
    {
      "id": 86,
      "name": "property_86",
      "label": "Type of Question",
      "value": [
        "90"
      ],
      "textValue": [
        "Other"
      ]
    },
    {
      "id": 69,
      "name": "property_69",
      "label": "Client",
      "value": [
        "82"
      ],
      "textValue": [
        "BigFoot Inc."
      ]
    }
  ]
}

MyCode:


import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "net/url"
)

var body = []byte(`JSON HERE
`)

type TiketData struct {
    Struct here
}

func main() {
var data TiketData

    json_err := json.Unmarshal(body, &data)
    if json_err != nil {
        fmt.Println(json_err)
    }

    for _, customFields := range data.CustomFields {
        fmt.Println(fmt.Sprintf("%#v", customFields))
    }
}

CodePudding user response:

Firstly, you need to define struct type for your JSON. I used auto-generated struct type but you can divide into multiple ones. Then, just apply the same steps for unmarshalling and access the variable. I hope it will solve your problem.

package main

import (
    "encoding/json"
    "fmt"
)

var j = `{
  "id": 759,
  "author": {
    "id": 1,
    "name": "Gogi Na Vole",
    "completedOn": "Never",
    "custom_fields": [
      {
        "id": 86,
        "name": "property_86",
        "label": "Type of Question",
        "value": [
          "90"
        ],
        "textValue": [
          "Other"
        ]
      },
      {
        "id": 69,
        "name": "property_69",
        "label": "Client",
        "value": [
          "82"
        ],
        "textValue": [
          "BigFoot Inc."
        ]
      }
    ]
  }
}`

type Data struct {
    Id     int `json:"id"`
    Author struct {
        Id           int    `json:"id"`
        Name         string `json:"name"`
        CompletedOn  string `json:"completedOn"`
        CustomFields []struct {
            Id        int      `json:"id"`
            Name      string   `json:"name"`
            Label     string   `json:"label"`
            Value     []string `json:"value"`
            TextValue []string `json:"textValue"`
        } `json:"custom_fields"`
    } `json:"author"`
}

func main() {
    var data *Data
    err := json.Unmarshal([]byte(j), &data)
    if err != nil {
        fmt.Println(err.Error())
        return
    }

    textVal := data.Author.CustomFields[1].TextValue
    fmt.Println(textVal)
}

Output will be:

[BigFoot Inc.]

Go Playground

  • Related