在python中创建一个json输出

时间:2016-12-23 17:47:59

标签: python json beautifulsoup

我正在尝试以json形式返回函数的响应。输出是一个列表,每个元素都是一个字典。我打印输出时没有看到任何错误。当我遍历输出时出现问题。我逐个得到输出中的所有字符。请参阅示例代码和示例输出以获得正确理解。

代码:

BundleConfig

“打印匹配”,即上面代码中的output1给出了以下输出:

import requests
import json
import sys
from bs4 import BeautifulSoup
from collections import OrderedDict

class Cricbuzz():
    url = "http://synd.cricbuzz.com/j2me/1.0/livematches.xml"
    def __init__(self):
        pass

    def getxml(self,url):
        try:
            r = requests.get(url)
        except requests.exceptions.RequestException as e: 
            print e
            sys.exit(1)
        soup = BeautifulSoup(r.text,"html.parser")
        return soup

    def matchinfo(self,match):
        d = OrderedDict()
        d['id'] = match['id']
        d['srs'] = match['srs']
        d['mchdesc'] = match['mchdesc']
        d['mnum'] = match['mnum']
        d['type'] = match['type']
        d['mchstate'] = match.state['mchstate']
        d['status'] = match.state['status']
        return d

    def matches(self):
        xml = self.getxml(self.url)
        matches = xml.find_all('match')
        info = []
        for match in matches:
            info.append(self.matchinfo(match))
        data = json.dumps(info)
        return data 
c = Cricbuzz()
matches = c.matches()
print matches #print matches -  output1
for match in matches:
    print match #print match -  output2

但是“打印匹配”,即for循环中上面代码中的output2给出了这个输出:

[
    {
        "status": "Coming up on Dec 24 at 01:10 GMT", 
        "mchstate": "nextlive", 
        "mchdesc": "AKL vs WEL", 
        "srs": "McDonalds Super Smash, 2016-17", 
        "mnum": "18TH MATCH", 
        "type": "ODI", 
        "id": "0"
    }, 
    {
        "status": "Ind U19 won by 34 runs", 
        "mchstate": "Result", 
        "mchdesc": "INDU19 vs SLU19", 
        "srs": "Under 19 Asia Cup, 2016", 
        "mnum": "Final", 
        "type": "ODI", 
        "id": "17727"
    }, 
    {
        "status": "PRS won by 48 runs", 
        "mchstate": "Result", 
        "mchdesc": "PRS vs ADS", 
        "srs": "Big Bash League, 2016-17", 
        "mnum": "5th Match", 
        "type": "T20", 
        "id": "16729"
    }
]

如您所见,一个角色从匹配开始打印在每一行上。我想在打印匹配时获取字典对象。

4 个答案:

答案 0 :(得分:1)

如果您在返回json.dumps之前就像在info上一样致电data,则该值会转换为json 字符串。如果你想遍历迭代,json字符串表示,你必须从json中加载数据。

考虑:

import json

info = [ { "a": 1}, { "b": 2} ]
data = json.dumps(info,indent=2)
print data
for i in data:
    print i
for i in json.loads(data):
    print i


$ python t.py
[
  {
    "a": 1
  },
  {
    "b": 2
  }
]
[




{






"
a
"
:

1




}
,





{








"
b
"
:

2




}


]
{u'a': 1}
{u'b': 2}

答案 1 :(得分:1)

    def matches(self):
        xml = self.getxml(self.url)
        matches = xml.find_all('match')
        info = []
        for match in matches:
            info.append(self.matchinfo(match))
        data = json.dumps(info) # This is a string
        return data             # This is a string

c = Cricbuzz()
matches = c.matches()           # This is a string
print matches 
for match in matches:           # Looping over all characters of a string
    print match 

我想你只想要return info,这是一个列表。当你确实需要JSON时,你可以稍后在该函数之外json.dumps()

或者,如果您确实希望该函数返回JSON字符串,则必须将其解析回列表。

for match in json.loads(matches): 

答案 2 :(得分:1)

matches是一个JSON字符串,而不是字典,所以for match in matches:遍历字符串中的字符。

如果你想要字典,该函数应该返回info而不是json.dumps(info)。或者你可以这样做:

for match in json.loads(matches):

将JSON解析回字典。

通常,您应该将程序中的数据作为字典和列表等结构化类型进行移动,并且只有在通过网络发送或存储到文件中时才将它们转换为JSON或从JSON转换。

答案 3 :(得分:0)

Json.dumps返回一个字符串。

如果您希望在迭代过程中从列表中获取每个dict,您可以将响应包装到:

matches = json.loads(matches)

顺便说一下,以前将它作为一个简单的JSON验证转储它是件好事,因为它使得有效的JSON无效:首先用双引号替换单引号,等等。'为什么我建议你不要跳过json.dump,因为你正在尝试做。