Python json字典到数组

时间:2013-04-09 02:55:50

标签: python arrays json dictionary

我在理解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

这意味着信息[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等等

1 个答案:

答案 0 :(得分: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