0

我在理解 json 字典和数组时遇到了一些麻烦。我有一个从网站上抓取信息的脚本。

models.txt 只是型号的列表,例如

30373
30374
30375

和 json_descriptions.txt 是我想要的键列表

sku
price
listprice
issoldout

代码是:

import urllib
import re
import json

modelslist = open("models.txt").read()
modelslist = modelslist.split("\n")
descriptionlist = open("json_descriptions.txt").read()
descriptionlist = descriptionlist.split("\n")

for model in modelslist:
    htmltext = urllib.urlopen("http://dx.com/p/GetProductInfoRealTime?skus="+model)
    htmltext = json.load(htmltext)
    if htmltext['success'] == True:
        def get_data(dict_index, key):
            return htmltext[u"data"][dict_index][key]
        for description in descriptionlist:
           info = description, (get_data(0,description))
           print info
    else:
       print "product does not exist"

如果我打印出信息,我会得到:

sku 30373
price 9.10
listprice 17.62
issoldout False

所以这意味着 info[0] 是:

sku
price
listprice
issoldout

和 info[1] 是:

30373
9.10
17.62
False

我想知道是否有办法可以做到这一点:循环 1 =['sku','30373','price','4.90','listprice','0','issoldout','False'] 循环 2 =['sku','30374','price','10.50','listprice','0','issoldout','False']

info[0] = sku info[1] = 30373 info[2] = price info[3] = 4.90 info[4] = listprice info[5] = 0 info[6] = issoldout info[7] = False然后使用新列表重复此操作以进行下一个循环。

我试过使用info = json.dumps(info),但这只是给出info[0] = [[[[等等info[1] = """" info[2] = spli

4

1 回答 1

1

像这样?

info = []
for model in modelslist:
    htmltext = urllib.urlopen("http://dx.com/p/GetProductInfoRealTime?skus="+model)
    htmltext = json.load(htmltext)
    if htmltext['success'] == True:
        def get_data(dict_index, key):
            return htmltext[u"data"][dict_index][key]
        for description in descriptionlist:
            info.append(description)
            info.append(get_data(0,description))
print info
于 2013-04-09T03:16:41.443 回答