我已经设置了一个Jupyter Notebook
连接我的Postgresql database
,调用表中的数据,并将机器学习模型从API应用到这些数据,但是我一直得到一个TypeError: the JSON object must be str, not 'DetailedResponse'
。
我的笔记本被分为三个单元,为了清楚起见,我把它们放在下面:
from watson_developer_cloud import NaturalLanguageClassifierV1
import pandas as pd
import psycopg2
import json
conn_string = 'host={} port={} dbname={} user={} password={}'.format('119.203.10.242', 5432, 'mydb', 'locq', 'Mypass***')
conn_cbedce9523454e8e9fd3fb55d4c1a52e = psycopg2.connect(conn_string)
data_df_1 = pd.read_sql('SELECT description from public."search_product"', con=conn_cbedce9523454e8e9fd3fb55d4c1a52e)
natural_language_classifier = NaturalLanguageClassifierV1(
iam_apikey='F76ugy8hv1s3sr87buhb7564vb7************'
)
classes = natural_language_classifier.classify('7818d2s519-nlc-1311', data_df_1.to_json())
print(json.loads(classes, indent=2))
以及完整的错误输出:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-b6b7d122a500> in <module>()
2
3 classes = natural_language_classifier.classify('7818d2s519-nlc-1311', data_df_1.to_json())
----> 4 print(json.loads(classes, indent=2))
/opt/conda/envs/DSX-Python35/lib/python3.5/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
310 if not isinstance(s, str):
311 raise TypeError('the JSON object must be str, not {!r}'.format(
--> 312 s.__class__.__name__))
313 if s.startswith(u'\ufeff'):
314 raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
TypeError: the JSON object must be str, not 'DetailedResponse'
我已经尝试了很多方法来实现这个目标,但是现在我完全陷入了困境,我找不到解决这个问题的方法,或者我可能不太理解代码来解决它。
请帮忙。
编辑
这个API在输出中生成一个头,所以当我尝试序列化时会得到一个错误,有没有方法删除这个头?
输出:
TypeError: {'Content-Security-Policy': "default-src 'none'", 'Content-Type': 'application/json', 'Content-Encoding': 'gzip', 'Expires': '0', 'X-Backside-Transport': 'OK OK', 'X-DP-Transit-ID': 'gateway01-1254538093', 'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache', 'Connection': 'keep-alive', 'x-global-transaction-id': '7ecac92c59876gfjbb6d', 'Vary': 'Accept-Encoding', 'X-Content-Type-Options': 'nosniff', 'Strict-Transport-Security': 'max-age=31536000;', 'X-DP-Watson-Tran-ID': 'gateway01-125765453', 'X-EdgeConnect-MidMile-RTT': '19', 'X-EdgeConnect-Origin-MEX-Latency': '498', 'Content-Length': '868', 'Date': 'Thu, 23 May 2019 17:15:58 GMT', 'X-XSS-Protection': '1'} is not JSON serializable
最佳答案
我不熟悉这个图书馆,但我会设法解决你的问题。
from watson_developer_cloud import NaturalLanguageClassifierV1
import pandas as pd
import psycopg2
import json
conn_string = 'host={} port={} dbname={} user={} password={}'.format('119.203.10.242', 5432, 'mydb', 'locq', 'Mypass***')
conn_cbedce9523454e8e9fd3fb55d4c1a52e = psycopg2.connect(conn_string)
data_df_1 = pd.read_sql('SELECT description from public."search_product"', con=conn_cbedce9523454e8e9fd3fb55d4c1a52e)
natural_language_classifier = NaturalLanguageClassifierV1(
iam_apikey='F76ugy8hv1s3sr87buhb7564vb7************'
)
classes = natural_language_classifier.classify('7818d2s519-nlc-1311', data_df_1.to_json())
data_dict = classes._to_dict() # this will returns dict
data_dict.pop('headers', None) # remove headers key
print(data_dict) # This shows you dictionary in terminal
# if you want to serialize this and save on disk, you should make json serialization for example.
json_data = json.dumps(data_dict)
print(json_data) # this shows your string(json) in terminal
也试试这个方法。
关于python - TypeError:JSON对象必须为str,而不是'DetailedResponse',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56279495/