0

A server is sending back such a response:

me@linux:~> curl -X GET http://*.*.*.*:8080/profiles

[
        {
                "ProfileID": 1,
                "Title": "65micron"
        },
        {
                "ProfileID": 2,
                "Title": "80micron"
        }
]

I have tried this solution to parse the response as JSON but it only works if the server response is like this:

{
    "array": [
        {
                "ProfileID": 1,
                "Title": "65micron"
        },
        {
                "ProfileID": 2,
                "Title": "80micron"
        }
    ]
}

Does anybody know how I can parse the server response as JSON?


One idea which occurred to me is to add { "array": to the beginning of http.Response.Body buffer and also add } to the its end, then use the standard solution. However, I'm not sure if that's the best idea.

2
  • 2
    Your json isn't valid, you are adding an extra ',' at the end of your objects. You can validate it using jsonlint.com. Correct it and try again Commented Dec 9, 2018 at 13:39
  • @AhmedEssam Thanks, my JSONs are super lengthy. I just pasted two key/values here as samples and I forgot to remove the extra , I'm going to fix my question now Commented Dec 9, 2018 at 13:41

2 Answers 2

2

You can unmarshal directly into an array

data := `[
    {
        "ProfileID": 1,
        "Title": "65micron"
    },
    {
        "ProfileID": 2,
        "Title": "80micron"
    }]`

type Profile struct {
    ProfileID int
    Title     string
}

var profiles []Profile

json.Unmarshal([]byte(data), &profiles)

You can also read directly from the Request.Body.

func Handler(w http.ResponseWriter, r *http.Request) {

    var profiles []Profile
    json.NewDecoder(r.Body).Decode(&profiles)
    // use `profiles`
}

Playground

Sign up to request clarification or add additional context in comments.

Comments

1

You should define a struct

type Profile struct {
    ID int `json:"ProfileID"`
    Title string `json:"Title"`
}

After that decode response

var r []Profile
err := json.NewDecoder(res.Body).Decode(&r)

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.