0

I'm using python 2.7.15. I've written a code where I executed AWS CLI using subprocess and I want to load output as json to process further. Code and error on execution are as follows:

output=subprocess.check_output(['aws','cloudwatch','get-metric-statistics','--namespace','AWS/ELB','--metric-name','RequestCount','--statistics','Sum','--period','3600','--dimensions','Name=LoadBalancerName,Value=prod-mapissl-asphalt','--start-time',otime,'--end-time',ctime])
print(output)

Ouput received:

RequestCount DATAPOINTS 468240.0    2018-11-07T09:12:00Z    Count

Output expected in below format:

b'{\n    "Datapoints": [\n        {\n            "Timestamp": "2018-11-07T08:03:00Z", \n            "Sum": 483274.0, \n            "Unit": "Count"\n        }\n    ], \n    "Label": "RequestCount"\n}\n'
483274.0

What to do to fix this? because of this I'm unable to run json.load(output).

When I run json.load(output), below stacktrace comes on run:

Traceback (most recent call last):
  "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
Igoranze
  • 1,506
  • 13
  • 35
  • Possible duplicate of [bytes-to-a-string](https://stackoverflow.com/questions/606191/convert-bytes-to-a-string) – Albin Paul Nov 07 '18 at 09:38

1 Answers1

0

aws by default outputs information in a string format. You need to change that to json using the --output option to make it json before parsing it this way.

If you want programmatic access, I recommend that use boto directly rather than rely on shelling out and parsing command line output. That's a last resort option and a flaky one at best.

Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169