【问题标题】:Python json dictionary to arrayPython json字典到数组
【发布时间】:2013-04-09 02:55:50
【问题描述】:

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

而信息[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 = json.dumps(info),但这只会给出info[0] = [[[[info[1] = """" info[2] = spli 等等

【问题讨论】:

  • 你确定这是一个数组而不是字典吗?您使用它的方式表明后者。
  • 是的,我的错……还在学习,我会编辑它。

标签: python arrays json dictionary


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    • 2015-10-17
    • 2018-05-04
    相关资源
    最近更新 更多