gpt4 book ai didi

python - 将字典列表传递给接受 json 文件的函数

转载 作者:行者123 更新时间:2023-12-01 09:29:23 25 4
gpt4 key购买 nike

我有一个字典列表,我想将其传递到接受 json 文件的函数中。

我当前的方法是(1)使用 json.dumps() 将字典列表转换为 json 并 (2) 通过 StringIO() 将其作为参数传递>

我收到错误。 AttributeError:“str”对象没有属性“decode”

我不确定如何解决这个问题,或者即使我使用了正确的方法。任何帮助表示赞赏。

编辑:

代码示例

import tdclient as td
import json
from io import StringIO

l = [{'a': 1}, {'b':2}, {'c':3}]
l_json = json.dumps(l)

with td.Client(TD_APIKEY) as con:
con.import_file('test', 'temp', 'json', StringIO(l_json))

和错误:

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-64-d81f043acd58> in <module>()
7
8 with td.Client(TD_APIKEY) as con:
----> 9 con.import_file('test', 'temp', 'json', StringIO(l_json))

~/anaconda3/lib/python3.6/site-packages/tdclient/client.py in import_file(self, db_name, table_name, format, file, unique_id)
605 Returns: float represents the elapsed time to import data
606 """
--> 607 return self.api.import_file(db_name, table_name, format, file, unique_id=unique_id)
608
609 def results(self):

~/anaconda3/lib/python3.6/site-packages/tdclient/import_api.py in import_file(self, db, table, format, file, unique_id, **kwargs)
61 Returns: float represents the elapsed time to import data
62 """
---> 63 with contextlib.closing(self._prepare_file(file, format, **kwargs)) as fp:
64 size = os.fstat(fp.fileno()).st_size
65 return self.import_data(db, table, "msgpack.gz", fp, size, unique_id=unique_id)

~/anaconda3/lib/python3.6/site-packages/tdclient/api.py in _prepare_file(self, file_like, fmt, **kwargs)
426 packer = msgpack.Packer()
427 with contextlib.closing(self._read_file(file_like, fmt, **kwargs)) as items:
--> 428 for item in items:
429 try:
430 mp = packer.pack(item)

~/anaconda3/lib/python3.6/site-packages/tdclient/api.py in _read_json_file(self, file_like, **kwargs)
471 # current impl doesn't torelate any JSON parse error
472 for s in file_like:
--> 473 record = json.loads(s.decode("utf-8"))
474 self._validate_record(record)
475 yield record

AttributeError: 'str' object has no attribute 'decode'

最佳答案

Import_file 需要 BytesIO 而不是 StringIO(请参阅其 test )

试试这个

import tdclient as td
import json
from io import BytesIO

l = [{'a': 1}, {'b':2}, {'c':3}]
l_json = json.dumps(l)

with td.Client(2) as con:
con.import_file('test', 'temp', 'json', BytesIO(bytes(l_json, 'utf-8')))

我们正在编码只是让它解码,但它应该可以工作。我没有 API key 来进一步验证,但我克服了您提到的错误。

关于python - 将字典列表传递给接受 json 文件的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50092998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com