首页 > 解决方案 > 直接从子进程输出解析 json 输出

问题描述

我无法弄清楚如何直接从子进程输出解析 json 输出。

代码片段

cmd = ['./mmdbinspect', '--db', '/usr/local/var/GeoIP/GeoLite2-City.mmdb', ip]
        # result returns json
        result = subprocess.run(cmd, stdout=subprocess.PIPE)
        result = json.loads(result)
        # parse & print
        print(result[0]['Lookup'])
        print(result[0]['Records'][0]['Record']['country']['iso_code'])
        print(result[0]['Records'][0]['Record']['country']['names']['en'])

如果我将结果写入文件,然后执行 json.load 它按预期工作,但我想合并并跳过该步骤。

回溯错误

TypeError: the JSON object must be str, bytes or bytearray, not CompletedProcess

标签: pythonjsonsubprocess

解决方案


从文档返回的实例将具有属性 args、returncode、stdout 和 stderr。要使用它,请从标准输出加载 json 字符串。

result = json.loads(result.stdout)

推荐阅读