英文:
JSON decode from url in Go
问题
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "https://api.twitter.com/1.1/search/tweets.json"
response, err := http.Get(url)
if err != nil {
fmt.Println(err)
return
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err)
return
}
var result map[string]interface{}
err = json.Unmarshal(body, &result)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(result)
}
英文:
I have my php code. How to create something like this in Go?
<?php
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$context = stream_context_create(array(
'http' => array(
'ignore_errors'=>true,
'method'=>'GET'
)
));
$response = json_decode(file_get_contents($url, false, $context));
print_r($response);
?>
答案1
得分: 4
包括这样的内容:
package main
import (
"encoding/json"
"fmt"
"net/http"
)
func main() {
resp, err := http.Get("https://api.twitter.com/1.1/search/tweets.json")
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Printf("%#v\n", resp)
dec := json.NewDecoder(resp.Body)
if dec == nil {
panic("Failed to start decoding JSON data")
}
json_map := make(map[string]interface{})
err = dec.Decode(&json_map)
if err != nil {
panic(err)
}
fmt.Printf("%v\n", json_map)
}
英文:
Something like this:
package main
import (
"encoding/json"
"fmt"
"net/http"
)
func main() {
resp, err := http.Get("https://api.twitter.com/1.1/search/tweets.json")
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Printf("%#v\n", resp)
dec := json.NewDecoder(resp.Body)
if dec == nil {
panic("Failed to start decoding JSON data")
}
json_map := make(map[string]interface{})
err = dec.Decode(&json_map)
if err != nil {
panic(err)
}
fmt.Printf("%v\n", json_map)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论