简体   繁体   中英

Parse json output directly from a subprocess output

I can't figure out how parse json output directly from a subprocess output.

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.

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 . To use it, load the json string from stdout.

result = json.loads(result.stdout)

这应该有效

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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