首页 > post 请求获取 json

post 请求获取 json

用 Python 或者 C# 如何实现 post 一个请求,并获取返回的 Json, 并解析。
用 fiddler 查看得到的 post。

如:http://example.com/json_svr/query/?u=1&c=481773
然后查看 fiddler 中的 json 显示如:ask_q=12
但是看不大明白,不知道怎么获取 ask_q 这个值。

由于网络知识欠缺,希望能尽量解释的详细点。非常感谢。


返回的json实质上是个json格式的字符串,那么1)你可以把他当字符串处理,可以通过正则匹配的你需要的值,2)把json反序列化,之后想取值就很容易了


不建议自己用正则处理,基本所有的编程语言里都有json处理的库,比如在python中,可以这样做

import json
import urllib2

data = json.load(urllib2.urlopen("https://api.github.com/users/defunkt"))

上面的代码 使用get请求github的api,当然也可以使用post方法,可以使用requests这个库,更加方便

结果

{u'public_repos': 101, u'site_admin': True, u'subscriptions_url': u'https://api.github.com/users/defunkt/subscriptions', u'gravatar_id': u'b8dbb1987e8e5318584865f880036796', u'hireable': True, u'id': 2, u'followers_url': u'https://api.github.com/users/defunkt/followers', u'following_url': u'https://api.github.com/users/defunkt/following{/other_user}', u'blog': u'http://chriswanstrath.com/', u'followers': 12921, u'location': u'San Francisco', u'type': u'User', u'email': u'chris@github.com', u'bio': u'', u'gists_url': u'https://api.github.com/users/defunkt/gists{/gist_id}', u'company': u'GitHub', u'events_url': u'https://api.github.com/users/defunkt/events{/privacy}', u'html_url': u'https://github.com/defunkt', u'updated_at': u'2013-12-22T08:59:46Z', u'received_events_url': u'https://api.github.com/users/defunkt/received_events', u'starred_url': u'https://api.github.com/users/defunkt/starred{/owner}{/repo}', u'public_gists': 284, u'name': u'Chris Wanstrath', u'organizations_url': u'https://api.github.com/users/defunkt/orgs', u'url': u'https://api.github.com/users/defunkt', u'created_at': u'2007-10-20T05:24:19Z', u'avatar_url': u'https://gravatar.com/avatar/b8dbb1987e8e5318584865f880036796?d=https%3A%2F%2Fidenticons.github.com%2Fc81e728d9d4c2f636f067f89cc14862c.png&r=x', u'repos_url': u'https://api.github.com/users/defunkt/repos', u'following': 208, u'login': u'defunkt'}
>>> data["login"]
u'defunkt'
>>>

如果使用requests模块

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print r.text
{
  ...
  "form": {
    "key2": "value2",
    "key1": "value1"
  },
  ...
}

顺便说下 http://httpbin.org 这个网站可以用来测试,非常方便

json 模块 http://docs.python.org/library/json.html
urilib 模块 http://docs.python.org/2/library/urllib.html
requests http://docs.python-requests.org/en/latest/user/quickstart/

【热门文章】
【热门文章】