为什么Python将我的dict视为str?

为什么Python将我的dict视为str?,python,json,python-3.x,python-requests,Python,Json,Python 3.x,Python Requests,这是我的JSON: 当我执行Python类型检查时,即: type(json) ... Output = dict 然后我尝试使用dict.items,我得到以下错误: AttributeError:'str'对象没有属性'items'(Python类型将其评估为Dict,但不知道为什么在我尝试使用.items时将其视为str) 我也试过ast.literal\u eval,但运气不好 同样的代码适用于以下JSON: 我在Windows10上使用Python3.7(64位) 我的完整代码如下:

这是我的JSON:

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

type(json) ... Output = dict
然后我尝试使用dict.items,我得到以下错误:

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

我也试过ast.literal\u eval,但运气不好

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

我在Windows10上使用Python3.7(64位)

我的完整代码如下:

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)
从烧瓶导入烧瓶
导入请求
导入json
导入系统
导入ast
app=烧瓶(名称)
@应用程序路径(“/”)
def getData():
请求\u数据=[
('url','https://www.amazon.com.au/dp/B078GH9T4R/ref=ods_bn_cat_aucc_h3_dot'),
]
r=requests.get('https://',auth=('XYZ@test.com“,”,数据=请求(数据)
结果={}
j=(r.content).解码('utf-8')
打印(j,file=sys.stderr)
d=json.dumps(j)
d1=ast.literal_eval(d)
data=json.loads(d1)
如果类型(数据)为dict:
打印(“****它是一个DICT***”,file=sys.stderr)
其他:
打印(“****它是一个字符串***”,file=sys.stderr)
打印(“*******************”,file=sys.stderr)
打印(类型(数据),文件=sys.stderr)
打印(数据,文件=sys.stderr)
打印(“*******************”,file=sys.stderr)
结果['url']=返回_项(列表(查找('url',数据)))
打印(返回项目(列表(查找('url',数据))),文件=sys.stderr)
结果['title']=返回_项(列表(查找('title',数据)))
结果['name']=返回_项(列表(查找('name',数据))[0]。拆分('124;'))
结果['image']=返回_项(列表(查找('image',数据)))
结果['current_price']=返回_项(列表(查找('price',data)))
返回json.dumps(结果)
#####################################################################    
def查找(键、字典):
对于dictionary.items()中的k,v:
如果k==键:
产量v
elif isinstance(v,dict):
对于查找结果(键,v):
产量结果
elif isinstance(v,列表):
对于v中的d:
对于查找结果(键,d):
产量结果
def返回_项目(列表):
如果len(列表)>0:
返回列表[0]
其他:
返回“不可用”
#打印(列出值[0]。获取('maintentity'),文件=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'
[2018-08-10 11:40:33463]应用程序中出现错误:/[GET]上出现异常
回溯(最近一次呼叫最后一次):
wsgi_应用程序中的文件“”,第2292行
response=self.full\u dispatch\u request()
文件“”,第1815行,完全发送请求
rv=自身处理用户异常(e)
文件“”,第1718行,在句柄\用户\异常中
重放(exc_类型、exc_值、tb)
文件“”,第35行,重新放置
增值
文件“”,第1813行,完全发送请求
rv=自我分派请求()
文件“”,第1799行,在调度请求中
返回self.view_函数[rule.endpoint](**req.view_参数)
getData中第37行的文件“”
结果['url']=返回_项(列表(查找('url',数据)))
文件“”,第60行,在“查找”中
对于查找结果(键,d):
文件“”,第60行,在“查找”中
对于查找结果(键,d):
文件“”,第60行,在“查找”中
对于查找结果(键,d):
文件“”,第52行,在“查找”中
对于dictionary.items()中的k,v:
AttributeError:“str”对象没有属性“items”

您的第一个JSON有一个字符串数组。在某个时刻,该数组的每个项都被传递到
find
,而不首先检查它是否是
dict

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

使用
isinstance(数据,dict)
,而不是
类型(数据)是dict
isinstance(数据,dict)也是给dict。你的救命恩人。。。我的大脑完全崩溃了,无法工作。它现在工作干净了。谢谢,继续贡献。
> [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'
    elif isinstance(v, list):
        for d in v:  # These d values are strings
            for result in find(key, d):
                yield result