如何从Python 2.7中的JSON输出中检索特定值?

时间:2017-11-14 10:44:36

标签: python json python-2.7 export-to-csv

我有一个Python 2.7脚本,如下所示:

import requests

    url = "https://example.net/rest/v1/m/4513452615415"

    querystring = {"client":"wzas"}

    payload = "{\r\n              \"sss\" : \""+msse+"\",\r\n\"VisitorId\":\""+mcid+"\",\r\n              \"thirdPartyId\": \""+tracking_id+"\",\r\n              \"contentAsJson\": \"true\",\r\n                             \"mbssParameters\": \r\n                             {        \r\n                             \"mboxMCGLH\": \"6\"     \r\n                             }\r\n}\r\n"
    headers = {
        'content-type': "application/json",
        'cache-control': "no-cache",
        'postman-token': "289f645d-1543-e6df-87fb-1cef88f110c5"
        }

    response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

    return (response.text)

输出发送到CSV文件,如下所示:

{"thirdPartyId":"559yZDIIs3XvFpLPhvjexK7/jYlT7ZwJXBpNc/ZS4A1saWdodG5pbmdzZWVkcw==","marketingId":"89137879111811717593914206190290951066814","edgeHost":"mrdge21.example.net","content":{"tnsVal":"931113:4:0","contentName":"examplecontent","revenue":14},"sessionId":"4513452615415"}

我怎么只输出contentName和tnsVal?

提前致谢 尼克

2 个答案:

答案 0 :(得分:3)

由于很明显你正在获得JSON,请尝试以下行:

import json
response_json = json.loads(response.text)
print(response_json['content']['contentName'], response_json['content']['tnsVal'])

答案 1 :(得分:2)

您可以尝试:

>>> import json
>>> data = json.loads(response.text)
>>> data["content"]["tnsVal"]
'931113:4:0'
>>> data["content"]["contentName"]
'examplecontent'