0

I have written following code to get array from JSON, and want to retrieve something like

[{"id":"id1","friendly":"friendly1"},{"id":"id2","friendly":"friendly2"}]

But it's empty:

[{"id":"","friendly":""},{"id":"","friendly":""}]

package main

import (
    "encoding/json"
    "fmt"
)

var input = `[
            {
                "not needed": "",
                "_source": {
                    "id": "id1",
                    "friendly": "friendly1"
                }
            },
            {
                "_source": {
                    "id": "id2",
                    "friendly": "friendly2"
                }
            }]`

type source struct {
    Id string `json:"id"`
    Friendly string `json:"friendly"`
}

func main() {
    result := make([]source, 0)
    sources := []source{}

    json.Unmarshal([]byte(input), &sources)

    for _, n := range sources {
        result = append(result, n)
    }
    out, _ := json.Marshal(result)
    fmt.Println(string(out))
}
2

1 Answer 1

1

Try creating an another struct that have one field called Source of type source. In my example below I called this struct outer. Your input should be an array of outer and your result an array of source.

Something like this:


import (
    "encoding/json"
    "fmt"
)

var input = `[
            {
                "not needed": "",
                "_source": {
                    "id": "id1",
                    "friendly": "friendly1"
                }
            },
            {
                "_source": {
                    "id": "id2",
                    "friendly": "friendly2"
                }
            }]`

type outer struct {
    Source source `json:"_source"`
}

type source struct {
    Id string `json:"id"`
    Friendly string `json:"friendly"`
}

func main() {
    result := make([]source, 0)
    sources := []outer{}

    json.Unmarshal([]byte(input), &sources)

    for _, n := range sources {
        result = append(result, n.Source)
    }
    out, _ := json.Marshal(result)
    fmt.Println(string(out))
}```
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.