-7

I have output like this

  >>> print output
  [{u'MachineId': u'0', u'Stdout': u'{"version":"2.1-beta2.1-xenial-amd64","url":"file:///tmp/juju-tools137740170/tools/released/juju-2.1-beta2-xenial-amd64.tgz","sha256":"70a1ec4e9d194f71506b9b2944357335d3dbe5386e7797de3ed71c12092ba774","size":24537713}'}]
 >>> type (output)
 <type 'list'>

 >>> print output[0]
 {u'MachineId': u'0', u'Stdout': u'{"version":"2.1-beta2.1-xenial-amd64","url":"file:///tmp/juju-tools137740170/tools/released/juju-2.1-beta2-xenial-amd64.tgz","sha256":"70a1ec4e9d194f71506b9b2944357335d3dbe5386e7797de3ed71c12092ba774","size":24537713}'}
 >>>
 >>> type (output[0])
 <type 'dict'>

In this I want to fetch sha256 value from the dictionary of output[0] and Stdout dict; Let me know is there a direct way to fetch this value in Python instead of iterating.

I got "TypeError: string indices must be integers" if I try to access them directly

     >>> print output[0]['Stdout']['sha256']
     Traceback (most recent call last):
     File "<console>", line 1, in <module>
     TypeError: string indices must be integers
Viswesn
  • 4,674
  • 2
  • 28
  • 45
  • 3
    Your `Stdout` is another JSON string, you'd have to decode that first before you have a dictionary with a `'sha245'` key. – Martijn Pieters Nov 29 '16 at 10:13
  • @MartijnPieters Let me know the way to fetch the value of sha256 from the output. – Viswesn Nov 29 '16 at 10:15
  • What s the problem here? If the structure and key names remain the same,you should easily be able to fetch using `output[0]['Stdout']['sha256']` – Mayur Buragohain Nov 29 '16 at 10:17
  • @MayurBuragohain; I tried it and I get the below error >>> print output[0]['Stdout']['sha256'] Traceback (most recent call last): File "", line 1, in TypeError: string indices must be integers – Viswesn Nov 29 '16 at 10:19
  • why negative comments of -4 to this question? Is that I asked something wrong :( – Viswesn Nov 29 '16 at 10:20

1 Answers1

1

You can get the sha256 value by converting your Stdout string to json, for example like this:

import json
print json.loads(output[0]['Stdout'])['sha256']
Alex
  • 21,273
  • 10
  • 61
  • 73
  • Why the need for for json.loads? From the question,its evident that output and output[0] are list and dict,respectively. – Mayur Buragohain Nov 29 '16 at 10:19
  • 1
    @MayurBuragohain,see the comment by Marty Pieters, based on the error reported by Viswesn Stdout is a JSON string and not a dictionary, – Alex Nov 29 '16 at 10:40