【问题标题】:Why is Python treating my dict as str?为什么 Python 将我的 dict 视为 str?
【发布时间】:2018-08-10 01:49:49
【问题描述】:

这是我的 JSON:

json = {"url":"https://www.amazon.com.au/Cenovis-Multivitamin-Minerals-Tablets-Value/dp/B07D2M5QKN/ref=br_asw_pdt-5","title":"Cenovis Multivitamin and Minerals Tablets Value Pack 200: Amazon.com.au: Health & Personal Care","additionalData":{"locality":{"country":"US","language":"en"}},"statusCode":"200","items":[{"@type":"WebPage","description":"Cenovis Multivitamin and Minerals Tablets Value Pack 200: Amazon.com.au: Health & Personal Care","name":"Cenovis Multivitamin and Minerals Tablets Value Pack 200: Amazon.com.au: Health & Personal Care","mainEntity":[{"@type":"Product","category":"Health & Household","name":"Cenovis Multivitamin and Minerals Tablets Value Pack 200","offers":{"@type":"Offer","availability":"InStock","price":9.8,"priceCurrency":"USD"},"image":"https://images-na.ssl-images-amazon.com/images/I/51qhXMVf3LL.jpg","additionalProperty":{"@type":"PropertyValue","name":"productFeatures","value":["Maintain memory, mood and cognitive function in the elderly (or with ageing), Maintain healthy bones and joints","No added yeast, gluten, lactose, sugar, artificial colours or flavours, artificial sweeteners, or dairy products.","Cenovis Multivitamin and Mineral contains 19 specially selected ingredients to provide daily nutritional support.","Assist your body with energy production","Support healthy immune function"]}}]}]}

当我进行 Python 类型检查时,即:

type(json) ... Output = dict

然后我尝试使用 dict.items 我得到以下错误:

AttributeError: 'str' object has no attribute 'items'(Python 类型将其评估为 Dict,但不知道为什么当我尝试使用 .items 时它被视为 Str)

我也尝试了 ast.literal_eval,但没有成功。

相同的代码适用于以下 JSON:

json = {"url":"https://www.tarocash.com.au/au/navy-bahamas-slim-shirt-171ls101","title":"Navy Bahamas Slim Stretch Shirt | Men's Apparel | Tarocash","favIcon":"https://cdn.tarocash.com.au/media/favicon/stores/5/favicon.png","additionalData":{"locality":{"country":"AU","language":"en"}},"statusCode":"200","items":[{"@type":"WebPage","description":"Navy Bahamas Slim Stretch Shirt available online at Tarocash. Shop Tarocash's smart casual men's clothes for special occasions, work and your weekend.","image":"https://tarocash.imgix.net/Tarocash/Products/171LS101_NVY_CROP.png","name":"BAHAMAS SLIM STRETCH SHIRT","mainEntity":[{"@type":"Product","offers":[{"@type":"Offer","availability":"InStock","priceCurrency":"AUD","price":89.99},{"@type":"Offer","availability":"InStock","priceCurrency":"AUD","price":89.99}],"name":"NAVY BAHAMAS SLIM STRETCH SHIRT"},{"@type":"SocialMediaAccounts","facebookPage":"tarocash","instagram":"tarocash"}]}]}

我在 Windows 10(64 位)上使用 Python 3.7

我的完整代码如下:

from flask import Flask
import requests
import json
import sys
import ast

app = Flask(__name__)

@app.route('/')
def getData():

    request_data = [
        ('url','https://www.amazon.com.au/dp/B078GH9T4R/ref=ods_bn_cat_aucc_h3_dot'),
    ]
    r = requests.get('https://<<My_API_Server>>', auth=('XYZ@test.com','<<my_valid_key>>'), data=request_data)

    result = {}

    j = (r.content).decode('utf-8')

    print(j, file=sys.stderr)

    d = json.dumps(j)
    d1 = ast.literal_eval(d)
    data = json.loads(d1)

    if type(data) is dict:
        print("**** ITS A DICT ***", file=sys.stderr)
    else:
        print("**** ITS A STRING ***", file=sys.stderr)

    print("**********************", file=sys.stderr)
    print(type(data), file=sys.stderr)
    print(data, file=sys.stderr)
    print("**********************", file=sys.stderr)

    result['url']    = return_item(list(find('url', data)))

    print(return_item(list(find('url', data))), file=sys.stderr)

    result['title']  = return_item(list(find('title', data)))
    result['name']   = return_item(list(find('name', data))[0].split('|'))
    result['image']  = return_item(list(find('image', data)))
    result['current_price'] = return_item(list(find('price', data)))

    return json.dumps(result)


#####################################################################    
def find(key, dictionary):
    for k, v in dictionary.items():
        if k == key:
            yield v
        elif isinstance(v, dict):
            for result in find(key, v):
                yield result
        elif isinstance(v, list):
            for d in v:
                for result in find(key, d):
                    yield result

def return_item(list):
    if len(list) > 0:
        return list[0]
    else:
        return "Not_Available"



#    print(list_values[0].get('mainEntity'),file=sys.stderr)

以下完全错误:

> [2018-08-10 11:40:33,463] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "<<My_Local_dev_Path>>", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "<<My_Local_dev_Path>>", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "<<My_Local_dev_Path>>", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "<<My_Local_dev_Path>>", line 35, in reraise
    raise value
  File "<<My_Local_dev_Path>>", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "<<My_Local_dev_Path>>", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "<<My_Local_dev_Path>>", line 37, in getData
    result['url']    = return_item(list(find('url', data)))
  File "<<My_Local_dev_Path>>", line 60, in find
    for result in find(key, d):
  File "<<My_Local_dev_Path>>", line 60, in find
    for result in find(key, d):
  File "<<My_Local_dev_Path>>", line 60, in find
    for result in find(key, d):
  File "<<My_Local_dev_Path>>", line 52, in find
    for k, v in dictionary.items():
AttributeError: 'str' object has no attribute 'items'

【问题讨论】:

  • 使用isinstance(data, dict),而不是type(data) is dict
  • isinstance(data, dict) 也在给 dict。

标签: python json python-3.x python-requests


【解决方案1】:

您的第一个 JSON 有一个字符串数组。在某些时候,该数组的每个项目都会传递给find,而无需先检查它是否为dict

    elif isinstance(v, list):
        for d in v:  # These d values are strings
            for result in find(key, d):
                yield result

【讨论】:

  • 你的救命稻草!!! ...我的大脑完全被烧坏了,无法工作。它现在工作干净。感谢并继续贡献。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多