-3

I am trying to parse a nested json on GO ,

the json looks like this:

{
    "id"   : 12345656,
    "date" : "2018-05-02-18-16-17",
    "lists" : [
     {
          "empoyee_id": "12343",
          "name": "User1"

      },
      {
          "contractor_id" : "12343",
          "name":  "User1"
       }, 
       {
          "contractor_id" : "12343",
          "name":  "User1"
       }
    ]
}

My struct

type Result struct {
  id    int64    `json:"id"`
  Date  string   `json:"date"`
  Lists []string `json:"lists"`
}

I am trying to access it using the following:

var result Result
json.Unmarshal(contents, &result)

How can I change the above to access to the employee_id or the contractor_id fields ?

mpm
  • 20,148
  • 7
  • 50
  • 55
jsor
  • 637
  • 4
  • 10
  • 1
    Your code is not valid Go. Please paste your actual, working code. Follow [this guide](https://stackoverflow.com/help/mcve) for producing a minimal, complete, verifiable example, so we can help y ou. – Jonathan Hall May 06 '18 at 18:52
  • And the JSON is not valid JSON, too. –  May 06 '18 at 18:54
  • i edited the question, i am sorry for the bad code , i am new to go – jsor May 06 '18 at 19:38
  • Possible duplicate of [Unmarshaling nested JSON objects in Golang](https://stackoverflow.com/questions/21268000/unmarshaling-nested-json-objects-in-golang) – reticentroot May 06 '18 at 21:34

1 Answers1

3

You need to use another type to store the nested data rather than a slice of strings like so:

package main

import (
    "fmt"
    "encoding/json"
)

var contents string = `{
    "id"   : 12345656,
    "date" : "2018-05-02-18-16-17",
    "lists" : [
     {
          "empoyee_id": "12343",
          "name": "User1"

      },
      {
          "contractor_id" : "12343",
          "name":  "User1"
       }, 
       {
          "contractor_id" : "12343",
          "name":  "User1"
       }
    ]
}`

type Result struct {
    ID    int64         `json:"id"`
    Date  string       `json:"date"`
    Lists []Contractor `json:"lists"`
}

type Contractor struct {
    ContractorID string `json:"contractor_id"`
    EmployeeID   string `json:"employee_id"`
    Name         string `json:"name"`
}

func main() {
    var result Result
    err := json.Unmarshal([]byte(contents), &result)
    if err != nil {
        panic(err)
    }
    fmt.Println(result)
}

Executable:

https://play.golang.org/p/7dYArgz1V8y

If you just want a single ID field on the nested object then you will need to do a custom unmarshal function on the result to work out which ID is present.

Iain Duncan
  • 3,139
  • 2
  • 17
  • 28