1

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?

2
  • 3
    you have to translate finaloutput as a python dictionary using the json module in python, specifically json.loads() Commented Jun 6, 2022 at 8:41
  • try print(json.loads(finaloutput)["id"]) Commented Jun 6, 2022 at 8:46

1 Answer 1

3

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"])
Sign up to request clarification or add additional context in comments.

1 Comment

Note that subprocess.check_output can be used to cover the capture and check options In a more concise form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.