Home > front end >  JSON - string value conversion to List
JSON - string value conversion to List

Time:12-08

Code used for extraction from JSON

import json
string = json.loads(data)
string['Body']

import base64
base64.b64decode(string['Body'])

bytes_data = base64.b64decode(string['Body'])
str(bytes_data, encoding='utf-8')

I have a following format that is extracted from JSON

"[{"id":"XXXX_U2_170216:XXXX_U2_170216:FBE_23015.Air","values":[{"v":"46","q":192,"t":"2021-10-28T13:47:59.7880096Z"}]},
{"id":"XXXX_U2_170216:XXXX_U2_170216:FBE_23015.Atomise","values":[{"v":"3.1","q":192,"t":"2021-10-28T13:47:59.7880096Z"}]}]"

Any idea about converting it to actual list

[{"id":"XXXX_U2_170216:XXXX_U2_170216:FBE_23015.Air","values":[{"v":"46","q":192,"t":"2021-10-28T13:47:59.7880096Z"}]},
{"id":"XXXX_U2_170216:XXXX_U2_170216:FBE_23015.Atomise","values":[{"v":"3.1","q":192,"t":"2021-10-28T13:47:59.7880096Z"}]}]

things I have tried :

list(bytearray(bytes_data))

for loop - for this output string, but this is a convoluted way to do it.
some more conversion stuff. looking for something that is compact.

CodePudding user response:

use json load method like this, suppose you have JSON array and want to convert in LIST then do following

import json
array = '{"Items": ["IPhone", "Earphone", "Powerbackup"]}'
data  = json.loads(array)
print (data['Items'])

CodePudding user response:

Reverse engineering your question....

Given a JSON file with base64 data

$ cat /tmp/data.json
{
  "Body": "W3siaWQiOiJYWFhYX1UyXzE3MDIxNjpYWFhYX1UyXzE3MDIxNjpGQkVfMjMwMTUuQWlyIiwidmFsdWVzIjpbeyJ2IjoiNDYiLCJxIjoxOTIsInQiOiIyMDIxLTEwLTI4VDEzOjQ3OjU5Ljc4ODAwOTZaIn1dfSwKeyJpZCI6IlhYWFhfVTJfMTcwMjE2OlhYWFhfVTJfMTcwMjE2OkZCRV8yMzAxNS5BdG9taXNlIiwidmFsdWVzIjpbeyJ2IjoiMy4xIiwicSI6MTkyLCJ0IjoiMjAyMS0xMC0yOFQxMzo0Nzo1OS43ODgwMDk2WiJ9XX1dCg=="
}

When read and extracted

import json
import base64
with open('/tmp/data.json') as f:
    string = json.load(f)
body = string['Body']

Then decoded... a list is returned

import pprint

l = json.loads(base64.b64decode(body)
pprint.pprint(l)
[{'id': 'XXXX_U2_170216:XXXX_U2_170216:FBE_23015.Air',
  'values': [{'v': '46', 'q': 192, 't': '2021-10-28T13:47:59.7880096Z'}]},
 {'id': 'XXXX_U2_170216:XXXX_U2_170216:FBE_23015.Atomise',
  'values': [{'v': '3.1', 'q': 192, 't': '2021-10-28T13:47:59.7880096Z'}]}]

CodePudding user response:

Use the built-in json module:

import json
data = json.loads(bytes_data)

It seems like you have a json inside a json, so load it twice:

import json
import base64

string = json.loads(data)
bytes_data = base64.b64decode(string['Body'])
output = json.loads(bytes_data)
  • Related