我正在尝试从返回 JSON 对象的 API 中获取响应,并将其转换为降价输出,以更易读的格式呈现。我正在尝试使用 pypandoc 来执行此操作,并且我花了很长时间弄清楚如何让它工作。
我希望以下内容可以根据 pandoc 的文档工作,但 pypandoc 文档和示例很少。
from ipwhois import IPWhois
obj = IPWhois('74.125.225.229')
results = obj.lookup_rdap(depth=1)
print(pypandoc.convert_text(results, 'json', 'md'))
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-6-6a5e630f5495> in <module>()
4 obj = IPWhois('74.125.225.229')
5 results = obj.lookup_rdap(depth=1)
----> 6 print(pypandoc.convert_text(results, 'json', 'md'))
C:\ProgramData\Anaconda3\lib\site-packages\pypandoc\__init__.py in convert_text(source, to, format, extra_args, encoding, outputfile, filters)
101 source = _as_unicode(source, encoding)
102 return _convert_input(source, format, 'string', to, extra_args=extra_args,
--> 103 outputfile=outputfile, filters=filters)
104
105
C:\ProgramData\Anaconda3\lib\site-packages\pypandoc\__init__.py in _convert_input(source, format, input_type, to, extra_args, outputfile, filters)
303
304 try:
--> 305 source = cast_bytes(source, encoding='utf-8')
306 except (UnicodeDecodeError, UnicodeEncodeError):
307 # assume that it is already a utf-8 encoded string
C:\ProgramData\Anaconda3\lib\site-packages\pypandoc\py3compat.py in cast_bytes(s, encoding)
37 # bytes == str on py2.7 -> always encode on py2
38 if not isinstance(s, bytes):
---> 39 return _encode(s, encoding)
40 return s
41
C:\ProgramData\Anaconda3\lib\site-packages\pypandoc\py3compat.py in _encode(u, encoding)
25 def _encode(u, encoding=None):
26 encoding = encoding or _DEFAULT_ENCODING
---> 27 return u.encode(encoding)
28
29
AttributeError: 'dict' object has no attribute 'encode'
如果有人知道更好的方法来转换它而不将其写成文件,如果您分享它,我将非常感激。
写入和读取文件版本:
from ipwhois import IPWhois
from pprint import pprint
import json, pypandoc
obj = IPWhois('74.125.225.229')
results = obj.lookup_rdap(depth=1)
pprint(results)
with open('data.json', 'w') as outfile:
json.dump(results, outfile)
output = pypandoc.convert_file('data.json', to='json', format='md',outputfile="data.md")