在Go中从URL解码JSON

huangapple go评论92阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2013年7月18日 19:48:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/17722625.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定