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

Parse json output directly from a subprocess output

我不知道如何直接从子进程输出解析 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

这应该有效

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

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

result = json.loads(result.stdout)