Python为什么将我的字典视为str?

时间:2018-08-10 01:49:50

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

这是我的JSON:

2018-08-10 09:38:00,009 - root - ERROR - Traceback (most recent call last):
  File "C:\jobtech-crawlers\crawler_parttimejobs.py", line 122, in dump_parttimejobs
    response = requests_retry_session().get(url=linkWqery)
NameError: global name 'linkWqery' is not defined

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

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"]}}]}]}

然后我尝试使用dict.items出现以下错误:

AttributeError:'str'对象没有属性'items'(Python类型将其评估为Dict,但不知道为什么当我尝试使用.items时将其视为Str))< / p>

我也尝试过ast.literal_eval,但是没有运气。

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

type(json) ... Output = dict

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

我的完整代码如下:

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"}]}]}

以下完整错误:

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)

1 个答案:

答案 0 :(得分:4)

您的第一个JSON具有字符串数组。在某个时候,该数组的每个项目都传递给 <!DOCTYPE html> <html> <head> <link rel="icon" href="langleylogo.png"> <link href='style.css' rel='stylesheet' type='text/css'> <link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet"> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> <meta charset="UTF-8"> <title>Langley</title> </head> <body> <div id="main"> <div class="parent"> <div class="left"> <div class="blueTop"> <input type="text" v-model="search" class="orgSearch" placeholder="Client | ToDo | Ticket"> </div> <div class="leftMiniContainer"> <template v-for="customer in filteredCustomers"> <div class="clientSearchCard"> <div class="orgVendor">V:</div> <div class="clientSearchCardValue">{{ customer.vendor }}</div> <br> <div class="orgVendor">O:</div> <div class="clientSearchCardValue">{{ customer.org }}</div> </div> </template> </div> </div> <div class="right "> <div class="right-nav "> <a href="index.html " class="selected "> <i class="header-glyph fa fa-home " aria-hidden="true "></i> Overview </a> <a href="status.html "> <i class="header-glyph fa fa-check-square-o " aria-hidden="true "></i> Status </a> <a href="client.html "> <i class="header-glyph fa fa-address-card " aria-hidden="true "></i> Client </a> <a href="ticket.html "> <i class="header-glyph fa fa-ticket " aria-hidden="true "></i> Ticket </a> <a href="todo.html "> <i class="header-glyph fa fa-list " aria-hidden="true "></i> To Do </a> <a href="files.html "> <i class="header-glyph fa fa-file-image-o " aria-hidden="true "></i> Files </a> <a href="features.html "> <i class="header-glyph fa fa-wrench " aria-hidden="true "></i> Features </a> <div class="right-nav-config "> <a href="config.html "> <i class="fa fa-user-circle " aria-hidden="true "></i> </a> </div> </div> <div class="clientListWrapper "> </div> </div> </div> </div> <script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script> <script src="app.js"></script> </body> </html> 而不先检查它是否为find

dict