简体   繁体   中英

How to extract values from subprocess.run json output command

I am trying to assign the values to the variable from the subprocess.run() command my code below

import subprocess
import_json_names = 'fileb://xxx/yyyy.json'

output = subprocess.run(['aws', 'apigateway', 'import-rest-api', '--body', f'{import_json_names}', '--profile', 'xxxx'],capture_output=True,
  text=True, check=True)
finaloutput = output.stdout
print(finaloutput)

after execute the above command, I m getting the following output

{
    "id": "123abc444",
    "name": "xxxx",
    "description": "xxx yy",
    "createdDate": "2022-06-06T13:41:44+05:30",
    "version": "2021-05-31T18:09:59Z",
    "apiKeySource": "HEADER",
    "endpointConfiguration": {
        "types": [
            "EDGE"
        ]
    },
    "disableExecuteApiEndpoint": false
}

I want to extract "id" values from the above output how to achieve the same?

Here's an example, I just echo'd a JSON object but it should work with your subprocess call too. (I added the extra shell argument to run for the demo but you can just ignore it for your use case.)

import subprocess
import json


output = subprocess.run(
    'echo {"id": "Woderick"}',
    capture_output=True,
    text=True,
    check=True,
    shell=True  # extra parameter for echo demo
)
print(output.stdout)
output_dict = json.loads(output.stdout)
print(output_dict["id"])

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