简体   繁体   English

直接从子进程输出解析 json 输出

[英]Parse json output directly from a subprocess output

I can't figure out how parse json output directly from a subprocess output.我无法弄清楚如何直接从子进程输出解析 json 输出。

code snippet代码片段

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'])

If I write result to file, then perform json.load it works as expected but I would like to combine and skip that step.如果我将结果写入文件,然后执行 json.load 它会按预期工作,但我想合并并跳过该步骤。

Traceback error回溯错误

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

From the docs The returned instance will have attributes args, returncode, stdout and stderr .从文档返回的实例将具有属性 args, returncode, stdout 和 stderr To use it, load the json string from stdout.要使用它,请从标准输出加载 json 字符串。

result = json.loads(result.stdout)

这应该有效

    result = json.load(result.read())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM