Home > Enterprise >  how to get the object with keys/value nested inside tuple from a Json output?
how to get the object with keys/value nested inside tuple from a Json output?

Time:05-23

how to get the object with keys/value nested inside tuple from a Json data ? I have been trying to get the below Json output for an api request and loaded the Json output - but i end up with this error

the JSON object must be str, bytes or bytearray, not tuple

i wrote a code like this:

output = json.loads(output)
print(output)

The output i get

('{\n  "architecture" : "x86_64",\n  "billingProducts" : null,\n  "devpayProductCodes" : null,\n  "marketplaceProductCodes" : null,\n  "imageId" : "****",\n  "instanceId" : "***",\n  "instanceType" : "t3.2xlarge",\n  "kernelId" : null,\n  "pendingTime" : "2022-05-19T17:32:35Z",\n  "privateIp" : "***",\n  "ramdiskId" : null,\n  "version" : "2017-09-30"\n}', '  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current\n                                 Dload  Upload   Total   Spent    Left  Speed\n\n  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0\n100    56  100    56    0     0  56000      0 --:--:-- --:--:-- --:--:-- 56000\n  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current\n                                 Dload  Upload   Total   Spent    Left  Speed\n\n  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0\n100   479  100   479    0     0   467k      0 --:--:-- --:--:-- --:--:--  467k\n')
output = json.loads(output)
  File "/usr/lib/python3.8/json/__init__.py", line 341, in loads
    raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not tuple

CodePudding user response:

As the error says, the variable output must be of type bytes, string, or bytearray.

If we take a deeper look, the tuple actually only contains one string element. So, I believe we're supposed to get that string element!

We can do so using this:

output = json.loads(output)[0] # Tuples are just like arrays

So, now the variable output is of type string!

If this doesn't work, perhaps try renaming the output variable as such:

variable = json.loads(output)[0]

Sorry if this is incorrect!

CodePudding user response:

According previous answer, it's almost correct. Must be

output = json.loads(output[0])

  • Related