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

时间:2018-04-30 01:44:19

标签: python json io

我有一个字典列表,我希望将其传递给接受json文件的函数。

我目前的做法是(1)使用json.dumps()将词典列表转换为json,(2)通过StringIO()

将其作为参数传递

我收到错误。 AttributeError: 'str' object has no attribute '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'

1 个答案:

答案 0 :(得分:1)

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密钥可以进一步验证,但我已经超出了您提到的错误。