2013-04-09 69 views
0

我在理解json字典和数组时遇到了一些麻烦。我有一个脚本是从网站上抓取信息。Python 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 

和信息[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] = skuinfo[1] = 30373info[2] = priceinfo[3] = 4.90info[4] = listpriceinfo[5] = 0info[6] = issoldoutinfo[7] = False然后用下一个循环的新列表重复该操作。

我一直在使用info = json.dumps(info)尝试,但只是给info[0] = [[[[info[1] = """"info[2] = spli

+0

你确定这是一个数组而不是字典吗?你使用它的方式表明后者。 – sapi 2013-04-09 02:58:31

+0

是啊,我的错......还在学习,我会编辑它。 – Travis 2013-04-09 03:03:13

回答

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