Created
January 21, 2024 03:59
-
-
Save ae5259/44bdd003397be72832d613c176be205d to your computer and use it in GitHub Desktop.
Read dynamic or unknown JSON response.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io" | |
"net/http" | |
) | |
func main() { | |
client := &http.Client{} | |
resp, err := client.Get("https://jsonplaceholder.typicode.com/todos/1") | |
if err != nil { | |
fmt.Println("Error:", err) | |
return | |
} | |
body, err := io.ReadAll(resp.Body) | |
if err != nil { | |
fmt.Println("Error:", err) | |
return | |
} | |
jsonData := []byte(body) | |
var result interface{} | |
err = json.Unmarshal(jsonData, &result) | |
if err != nil { | |
fmt.Println("Error:", err) | |
return | |
} | |
dataMap, ok := result.(map[string]interface{}) | |
if !ok { | |
fmt.Println("Invalid JSON structure") | |
return | |
} | |
title, titleExists := dataMap["title"].(string) | |
if titleExists { | |
fmt.Println("Title:", title) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment