Dynamic add list in to json-dict as float - python

Im running a python 3.7 script where im trying to remove quotes.
Im trying to add a dynamic list (x and y coordinates) to a json-dictionary but i keep getting quotes surrounding the list. I need the list to be inserted without these quotes.
Here is my code that im running:
#The dynamic list
polygon = ['0.124912491249125', '0.683368336833683', '0.128112811281128', '0.472147214721472', '-0.096909690969097', '0.444344434443444', '-0.196919691969197', '-0.533353335333533', '-0.64996499649965', '-0.427742774277428', '-0.290529052905291', '-0.266726672667267', '-0.237523752375237', '0.64996499649965']
list_polygon = []
for i,k in zip(polygon[0::2], polygon[1::2]):
data_polygon = ('['+str(i), str(k)+']')
data_polygon = str(data_polygon)
list_polygon.append(data_polygon)
list_polygon = str(list_polygon)
list_polygon = list_polygon.replace("'",'').replace("(",'').replace(")",'').replace("[[",'[').replace("]]",']')
cord_data = {'apiVersion': '1.3',
'context': '<client context>',
'params': {'cameras': [{'active': True, 'id': 1, 'rotation': 0}],
'configurationStatus': 5,
'profiles': [{'camera': 1,
'filters': [{'active': True,
'data': 1,
'type': 'timeShortLivedLimit'},
{'active': True,
'data': 5,
'type': 'distanceSwayingObject'},
{'active': True,
'data': [5, 5],
'type': 'sizePercentage'}],
'name': 'Profile 1',
'triggers': [{'data': [list_polygon],
'type': 'includeArea'}],
'uid': 1}]},
'method': 'setConfiguration'}
And i get the answer:
{'apiVersion': '1.3', 'context': '<client context>', 'params': {'cameras': [{'active': True, 'id': 1, 'rotation': 0}], 'configurationStatus': 5, 'profiles': [{'camera': 1, 'filters': [{'active': True, 'data': 1, 'type': 'timeShortLivedLimit'}, {'active': True, 'data': 5, 'type': 'distanceSwayingObject'}, {'active': True, 'data': [5, 5], 'type': 'sizePercentage'}], 'name': 'Profile 1', 'triggers': [{'data': ['[0.124912491249125, 0.683368336833683], [0.128112811281128, 0.472147214721472], [-0.096909690969097, 0.444344434443444], [-0.196919691969197, -0.533353335333533], [-0.64996499649965, -0.427742774277428], [-0.290529052905291, -0.266726672667267], [-0.237523752375237, 0.64996499649965]'], 'type': 'includeArea'}], 'uid': 1}]}, 'method': 'setConfiguration'}
As you see it adds a quote between the brackets (at the start and the end) 'triggers': [{'data': ['[ 0.124912491249125, 0.683368336833683], [0.128112811281128, 0.472147214721472], [-0.096909690969097, 0.444344434443444], [-0.196919691969197, -0.533353335333533], [-0.64996499649965, -0.427742774277428], [-0.290529052905291, -0.266726672667267], [-0.237523752375237, 0.64996499649965 ]']
Instead i want it to look like this:
'triggers': [{'data': [[ 0.124912491249125, 0.683368336833683], [0.128112811281128, 0.472147214721472], [-0.096909690969097, 0.444344434443444], [-0.196919691969197, -0.533353335333533], [-0.64996499649965, -0.427742774277428], [-0.290529052905291, -0.266726672667267], [-0.237523752375237, 0.64996499649965 ]]
The first and second must be paired.
The post i want to send should look like this:
cord_data = {'apiVersion': '1.3',
'context': '<client context>',
'params': {'cameras': [{'active': True, 'id': 1, 'rotation': 0}],
'configurationStatus': 5,
'profiles': [{'camera': 1,
'filters': [{'active': True,
'data': 1,
'type': 'timeShortLivedLimit'},
{'active': True,
'data': 5,
'type': 'distanceSwayingObject'},
{'active': True,
'data': [5, 5],
'type': 'sizePercentage'}],
'name': 'Profile 1',
'triggers': [{'data': [[0.124912491249125, 0.683368336833683],
[0.128112811281128, 0.472147214721472],
[-0.096909690969097, 0.444344434443444]
and so on],
'type': 'includeArea'}],
'uid': 1}]},
'method': 'setConfiguration'}
What im i doing wrong?

You make every effort to make it str first, when you need list of lists of floats.
polygon = ['0.124912491249125', '0.683368336833683', '0.128112811281128', '0.472147214721472', '-0.096909690969097', '0.444344434443444', '-0.196919691969197', '-0.533353335333533', '-0.64996499649965', '-0.427742774277428', '-0.290529052905291', '-0.266726672667267', '-0.237523752375237', '0.64996499649965']
list_polygon = [[float(i), float(k)] for i,k in zip(polygon[0::2], polygon[1::2])]
cord_data = {'apiVersion': '1.3',
'context': '<client context>',
'params': {'cameras': [{'active': True, 'id': 1, 'rotation': 0}],
'configurationStatus': 5,
'profiles': [{'camera': 1,
'filters': [{'active': True,
'data': 1,
'type': 'timeShortLivedLimit'},
{'active': True,
'data': 5,
'type': 'distanceSwayingObject'},
{'active': True,
'data': [5, 5],
'type': 'sizePercentage'}],
'name': 'Profile 1',
'triggers': [{'data': list_polygon,
'type': 'includeArea'}],
'uid': 1}]},
'method': 'setConfiguration'}
print(cord_data)
And a word of advise - don't forget Floating Point Arithmetic: Issues and Limitations

I guess you'd want something like this:
from pprint import pprint
#The dynamic list
polygon = ['0.124912491249125', '0.683368336833683', '0.128112811281128', '0.472147214721472', '-0.096909690969097', '0.444344434443444', '-0.196919691969197', '-0.533353335333533', '-0.64996499649965', '-0.427742774277428', '-0.290529052905291', '-0.266726672667267', '-0.237523752375237', '0.64996499649965']
list_polygon = []
for i,k in zip(polygon[0::2], polygon[1::2]):
# Don't duplicate convert to `str`, please. Data is already a string.
data_polygon = ([i, k])
# Remove this line, it messes it up if retained
# data_polygon = str(data_polygon)
list_polygon.append(data_polygon)
# Why are we converting all lists to string anyway??
# list_polygon = str(list_polygon)
# list_polygon = list_polygon.replace("'",'').replace("(",'').replace(")",'').replace("[[",'[').replace("]]",']')
# Convert all nested strings to floats
list_polygon = [list(map(float, data_polygon)) for data_polygon in list_polygon]
cord_data = {'apiVersion': '1.3',
'context': '<client context>',
'params': {'cameras': [{'active': True, 'id': 1, 'rotation': 0}],
'configurationStatus': 5,
'profiles': [{'camera': 1,
'filters': [{'active': True,
'data': 1,
'type': 'timeShortLivedLimit'},
{'active': True,
'data': 5,
'type': 'distanceSwayingObject'},
{'active': True,
'data': [5, 5],
'type': 'sizePercentage'}],
'name': 'Profile 1',
# Don't nest it within another list (unless needed)
# 'triggers': [{'data': [list_polygon],
'triggers': [{'data': list_polygon,
'type': 'includeArea'}],
'uid': 1}]},
'method': 'setConfiguration'}
pprint(cord_data)

Related

How to subtract key out of Json api response and check if there are more keys, and if so put them in a list?

So I have a complex problem, I have a JSON API response with the key: 'key' in 'persons'
but in some cases there is more than 1 'key', I tried to make a for loop to go through the response but it will print it like 20 times. Also, I have no idea to put those 'keys' in a list or a place where I can access them.
to make it a bit easier i have the response that i get out of my .request
{'id': 'a2b1109e-e142-4559-984c-3f9997b1db6a', 'externalId': None, 'name': 'tyr', 'description': '', 'client': '', 'reference': '56345', 'isMonitoring': False, 'monitoringSince': None, 'hasRiskProfile': True, 'riskProfile': 5, 'monitorFrequency': 4, 'mainBindable': None, 'organizationId': '65647b97-5ada-4362-bb3f-cae016722be6', 'userId': 'dd3cc015-e5cf-4a03-9408-74b102900836', 'createDate': '2021-03-23T11:29:55.2027037Z', 'updateDate': '2021-03-23T11:29:55.2027039Z', 'lastMonitorDate': '2021-03-23T11:29:55.2027039Z', 'persons': [{'firstname': 'ya', 'surname': 'o', 'dateOfBirth': '', 'updatedWithIdinIdentificationRequestPerson': None, 'relatedList': None, 'updatedWithIdinIdentificationRequestPersonDate': None, 'history': [], 'fullname': 'ya o', 'externalId': None, 'key': '8b92c210-eee6-4ab2-a093-48e4428af7f8', 'searchResults': [], 'requests': [], 'createDate': '2021-03-23T11:29:57.3853552Z', 'updateDate': '2021-03-23T11:29:57.3853553Z', 'archivedDate': None, 'isArchived': False, 'hasPepSearchResults': False, 'notes': []}], 'businesses': [], 'monitorIds': [], 'addresses': [], 'notifcations': [], 'monitors': []}
the number of keys can be different each time, so I will need to make a check to see if the key that gets back is already existing if so then do nothing, if the key is not existing then save that key in a variable.
here is a example of a response when there are 2 keys"key",
{'id': '44b2203b-b2c8-41f0-8fde-b697ec02a8c8', 'externalId': None, 'name': 'tyr', 'description': '', 'client': '', 'reference': '56345', 'isMonitoring': False, 'monitoringSince': None, 'hasRiskProfile': True, 'riskProfile': 5, 'monitorFrequency': 4, 'mainBindable': None, 'organizationId': '65647b97-5ada-4362-bb3f-cae016722be6', 'userId': 'dd3cc015-e5cf-4a03-9408-74b102900836', 'createDate': '2021-03-23T20:58:53.0345703Z', 'updateDate': '2021-03-23T20:58:53.0345705Z', 'lastMonitorDate': '2021-03-23T20:58:53.0345706Z', 'persons': [{'firstname': 'marnox', 'surname': 'bolier', 'dateOfBirth': '', 'updatedWithIdinIdentificationRequestPerson': None, 'relatedList': None, 'updatedWithIdinIdentificationRequestPersonDate': None, 'history': [], 'fullname': 'marnox bolier', 'externalId': None, 'key': '68e4a9ad-2431-490f-a216-61a0cbd81c57', 'searchResults': [{'at': '2021-03-23T20:58:54.6796804Z', 'totalHits': 0, 'type': None, 'results': [{'paymentRequired': False, 'service': None, 'source': 'CIR', 'items': [], 'count': 0}, {'paymentRequired': False, 'service': 'VaV61', 'source': 'Entity', 'items': [], 'count': 0}], 'requestable': {'id': 'bf9dea30-2f4a-467a-a7b1-6765ceaee517', 'name': 'marnox bolier', 'createDate': '2021-03-23T20:58:55.5409494Z', 'updateDate': '2021-03-23T20:58:55.5409495Z', 'type': 'NotFoundPerson', 'sourceKey': 'A135D3C449EA15C66B6444611E2C97EC', 'picture': None, 'properties': {}, 'resultKey': None, 'data': None, 'archivedDate': None, 'isArchived': False}, 'cachedResult': False}], 'requests': [{'id': '57866866-85c4-43d8-8caa-b47a90b12be4', 'name': 'marnox bolier (TO UPDATE)', 'createDate': '2021-03-23T20:58:56.3090064Z', 'updateDate': '2021-03-23T20:58:56.3090064Z', 'type': 'NotFoundPerson', 'sourceKey': 'AB1AD3379D84D5D2404CF8326CDA054D', 'picture': None, 'properties': {}, 'resultKey': None, 'data': None, 'archivedDate': None, 'isArchived': False}], 'createDate': '2021-03-23T20:58:53.912784Z', 'updateDate': '2021-03-23T20:58:53.912784Z', 'archivedDate': None, 'isArchived': False, 'hasPepSearchResults': True, 'notes': []}, {'firstname': 'marnix', 'surname': 'bolier', 'dateOfBirth': '', 'updatedWithIdinIdentificationRequestPerson': None, 'relatedList': None, 'updatedWithIdinIdentificationRequestPersonDate': None, 'history': [], 'fullname': 'marnix bolier', 'externalId': None, 'key': 'c0475154-530e-4802-b215-1d26a2c7f208', 'searchResults': [], 'requests': [], 'createDate': '2021-03-23T20:58:56.9078002Z', 'updateDate': '2021-03-23T20:58:56.9078002Z', 'archivedDate': None, 'isArchived': False, 'hasPepSearchResults': False, 'notes': []}], 'businesses': [], 'monitorIds': [], 'addresses': [], 'notifcations': [], 'monitors': []}
update i solved my first problem getting more than 1 key with a for loop:
for persons in api_response['persons']:
print(persons['key'])
output:
0b8eb227-0105-40a3-bc8b-8e3ef345a3f3
d9b68e7a-ffdd-44ea-86a4-ea4c541146b4
how can I only save the last result so in this case
d9b68e7a-ffdd-44ea-86a4-ea4c541146b4
Assuming you are using requests to fetch the data from the api your response will simply have a json() function attached. Meaning you can do something like this:
import requests
response = requests.get("example.com/api/random/endpoint")
data = response.json()
The json function in turn does the equivalent of json.loads() with the content of the response. Assuming your API returns a JSON object this will be converted to a dictionary (in accordance with the json conversion table.
After that you can follow go2nirvana's answer and manipulate this dictionary as you would any dict. For example using data.pop("key") to remove the value at that key, iterate over the dictionary, or whatever else you can do with a dictionary.
Admittedly your question is a bit vague and I am not sure exactly what you want to do with the data you recieve, but this is how you get that data in a form that is easy to work with within python.

Accessing specific data from JSON data (Python)

I am new to JSON in Python (forgive me if I word something incorrectly) and I am trying to parse JSON information I get from an API. I get the API information successfully, but when I attempt to extract the information that I need (specifically the 'name' value in the variable info). I can't seem to find anything on how to access it. The code is below:
# Importing JSON handling library for parsing GET request using requests library
import json
import requests
import ast
import collections
# API Endpoint
url = "https://fnbr.co/api/shop"
# API key
key = "" # key is usually here
# Defining Parameters
headers = {"x-api-key":key}
# Sending GET request
req = requests.get(url = url, headers = headers)
info = req.json()
info = info['data']['featured']
print(info)
And the output:
[{'id': '5e8743597576ec53deb18eeb', 'name': 'Deadpool Gear Bundle', 'price': '2,000', 'priceIcon': 'vbucks', 'priceIconLink': 'https://image.fnbr.co/price/icon_vbucks.png', 'images': {'icon': 'https://image.fnbr.co/bundle/5e8743597576ec53deb18eeb/icon.png', 'png': False, 'gallery': False, 'featured': False, 'resizeAvailable': True}, 'rarity': 'marvel', 'type': 'bundle', 'slug': 'deadpool-gear-bundle', 'readableType': 'Bundle', 'description': False, 'bundleSet': '5e87444f7576ec029cb18eef', 'bannerText': False, 'history': {'occurrences': 4, 'firstSeen': '2020-04-03T00:00:00.471Z', 'lastSeen': '2020-04-10T00:00:00.000Z', 'dates': ['2020-04-10T00:00:00.000Z', '2020-04-05T00:00:00.000Z', '2020-04-04T00:00:00.000Z', '2020-04-03T00:00:00.471Z']}}, {'id': '5e8fbb5d3cdac627afdebeb5', 'name': 'Deadpool Mashups', 'price': '2,000', 'priceIcon': 'vbucks', 'priceIconLink': 'https://image.fnbr.co/price/icon_vbucks.png', 'images': {'icon': 'https://image.fnbr.co/bundle/5e8fbb5d3cdac627afdebeb5/icon.png', 'png': False, 'gallery': False, 'featured': False}, 'rarity': 'marvel', 'type': 'bundle', 'slug': 'deadpool-mashups', 'readableType': 'Bundle', 'description': 'Outfit Bundle.', 'bundleSet': '5e8fba7a3cdac6863bdebeaf', 'bannerText': False, 'history': {'occurrences': 1, 'firstSeen': '2020-04-10T00:00:00.000Z', 'lastSeen': '2020-04-10T00:00:00.000Z', 'dates': ['2020-04-10T00:00:00.000Z']}}, {'id': '5e8742117576ec88f6b18ee0', 'name': 'Chimichanga!', 'price': '300', 'priceIcon': 'vbucks', 'priceIconLink': 'https://image.fnbr.co/price/icon_vbucks.png', 'images': {'icon': 'https://image.fnbr.co/emote/5e8742117576ec88f6b18ee0/icon.png', 'png': False, 'gallery': False, 'featured': False, 'resizeAvailable': True}, 'rarity': 'marvel', 'type': 'emote', 'slug': 'chimichanga', 'readableType': 'Emote', 'description': 'Too hot! Too hot!', 'bundleSet': False, 'bannerText': 'Collect the Set!', 'history': {'occurrences': 4, 'firstSeen': '2020-04-03T00:00:00.471Z', 'lastSeen': '2020-04-10T00:00:00.000Z', 'dates': ['2020-04-10T00:00:00.000Z', '2020-04-05T00:00:00.000Z', '2020-04-04T00:00:00.000Z', '2020-04-03T00:00:00.471Z']}}, {'id': '5e8741f37576ecfc79b18edd', 'name': "Scootin'", 'price': '500', 'priceIcon': 'vbucks', 'priceIconLink': 'https://image.fnbr.co/price/icon_vbucks.png', 'images': {'icon': 'https://image.fnbr.co/emote/5e8741f37576ecfc79b18edd/icon.png', 'png': False, 'gallery': False, 'featured': False, 'resizeAvailable': True}, 'rarity': 'marvel', 'type': 'emote', 'slug': 'scootin', 'readableType': 'Emote', 'description': 'Dangerously dainty.', 'bundleSet': False, 'bannerText': False, 'history': {'occurrences': 4, 'firstSeen': '2020-04-03T00:00:00.471Z', 'lastSeen': '2020-04-10T00:00:00.000Z', 'dates': ['2020-04-10T00:00:00.000Z', '2020-04-05T00:00:00.000Z', '2020-04-04T00:00:00.000Z', '2020-04-03T00:00:00.471Z']}}, {'id': '5e87422b7576ec21f5b18ee3', 'name': 'Dragacorn', 'price': '1,500', 'priceIcon': 'vbucks', 'priceIconLink': 'https://image.fnbr.co/price/icon_vbucks.png', 'images': {'icon': 'https://image.fnbr.co/glider/5e87422b7576ec21f5b18ee3/icon.png', 'png': False, 'gallery': False, 'featured': False, 'resizeAvailable': True}, 'rarity': 'marvel', 'type': 'glider', 'slug': 'dragacorn', 'readableType': 'Glider', 'description': 'Bask in its mutant rainbow glory.', 'bundleSet': False, 'bannerText': 'Collect the Set!', 'history': {'occurrences': 4, 'firstSeen': '2020-04-03T00:00:00.471Z', 'lastSeen': '2020-04-10T00:00:00.000Z', 'dates': ['2020-04-10T00:00:00.000Z', '2020-04-05T00:00:00.000Z', '2020-04-04T00:00:00.000Z', '2020-04-03T00:00:00.471Z']}}, {'id': '5e8fbafd3cdac6ed02debeb3', 'name': 'Cuddlepool', 'price': '1,500', 'priceIcon': 'vbucks', 'priceIconLink': 'https://image.fnbr.co/price/icon_vbucks.png', 'images': {'icon': 'https://image.fnbr.co/outfit/5e8fbafd3cdac6ed02debeb3/icon.png', 'png': False, 'gallery': False, 'featured': 'https://image.fnbr.co/outfit/5e8fbafd3cdac6ed02debeb3/featured.png', 'resizeAvailable': True}, 'rarity': 'marvel', 'type': 'outfit', 'slug': 'cuddlepool', 'readableType': 'Outfit', 'description': 'Ferociously furry.', 'bundleSet': False, 'bannerText': False, 'history': {'occurrences': 1, 'firstSeen': '2020-04-10T00:00:00.000Z', 'lastSeen': '2020-04-10T00:00:00.000Z', 'dates': ['2020-04-10T00:00:00.000Z']}}, {'id': '5e8fb9f33cdac69b0fdebead', 'name': 'Ravenpool', 'price': '1,500', 'priceIcon': 'vbucks', 'priceIconLink': 'https://image.fnbr.co/price/icon_vbucks.png', 'images': {'icon': 'https://image.fnbr.co/outfit/5e8fb9f33cdac69b0fdebead/icon.png', 'png': False, 'gallery': False, 'featured': 'https://image.fnbr.co/outfit/5e8fb9f33cdac69b0fdebead/featured.png', 'resizeAvailable': True}, 'rarity': 'marvel', 'type': 'outfit', 'slug': 'ravenpool', 'readableType': 'Outfit', 'description': 'Maximum darkness.', 'bundleSet': False, 'bannerText': False, 'history': {'occurrences': 1, 'firstSeen': '2020-04-10T00:00:00.000Z', 'lastSeen': '2020-04-10T00:00:00.000Z', 'dates': ['2020-04-10T00:00:00.000Z']}}, {'id': '5e8741d67576ecad85b18eda', 'name': 'Meaty Mallets', 'price': '800', 'priceIcon': 'vbucks', 'priceIconLink': 'https://image.fnbr.co/price/icon_vbucks.png', 'images': {'icon': 'https://image.fnbr.co/pickaxe/5e8741d67576ecad85b18eda/icon.png', 'png': False, 'gallery': False, 'featured': False, 'resizeAvailable': True}, 'rarity': 'marvel', 'type': 'pickaxe', 'slug': 'meaty-mallets', 'readableType': 'Pickaxe', 'description': "Give 'em a thwack.", 'bundleSet': False, 'bannerText': 'Collect the Set!', 'history': {'occurrences': 4, 'firstSeen': '2020-04-03T00:00:00.471Z', 'lastSeen': '2020-04-10T00:00:00.000Z', 'dates': ['2020-04-10T00:00:00.000Z', '2020-04-05T00:00:00.000Z', '2020-04-04T00:00:00.000Z', '2020-04-03T00:00:00.471Z']}}, {'id': '5db7ff1ac02d0515d20b054c', 'name': 'Riley', 'price': '1,200', 'priceIcon': 'vbucks', 'priceIconLink': 'https://image.fnbr.co/price/icon_vbucks.png', 'images': {'icon': 'https://image.fnbr.co/outfit/5db7ff1ac02d0515d20b054c/icon.png', 'png': False, 'gallery': False, 'featured': 'https://image.fnbr.co/outfit/5db7ff1ac02d0515d20b054c/featured.png', 'resizeAvailable': True}, 'rarity': 'rare', 'type': 'outfit', 'slug': 'riley', 'readableType': 'Outfit', 'description': 'The city is her playground.', 'bundleSet': False, 'bannerText': False, 'history': {'occurrences': 5, 'firstSeen': '2019-11-27T00:00:00.000Z', 'lastSeen': '2020-04-10T00:00:00.000Z', 'dates': ['2020-04-10T00:00:00.000Z', '2019-11-27T00:00:00.000Z', '2020-03-09T00:00:00.000Z', '2020-01-01T00:00:00.000Z', '2020-02-06T00:00:00.575Z']}}, {'id': '5db804ebc02d05322e0b059d', 'name': 'Wild X', 'price': '300', 'priceIcon': 'vbucks', 'priceIconLink': 'https://image.fnbr.co/price/icon_vbucks.png', 'images': {'icon': 'https://image.fnbr.co/wrap/5db804ebc02d05322e0b059d/icon.png', 'png': False, 'gallery': False, 'featured': 'https://image.fnbr.co/wrap/5db804ebc02d05322e0b059d/featured.png'}, 'rarity': 'uncommon', 'type': 'wrap', 'slug': 'wild-x', 'readableType': 'Wrap', 'description': 'Show your style.', 'bundleSet': False, 'bannerText': 'Collect the Set!', 'history': {'occurrences': 5, 'firstSeen': '2019-11-27T00:00:00.000Z', 'lastSeen': '2020-04-10T00:00:00.000Z', 'dates': ['2020-04-10T00:00:00.000Z', '2019-11-27T00:00:00.000Z', '2020-03-09T00:00:00.000Z', '2020-01-01T00:00:00.000Z', '2020-02-06T00:00:00.575Z']}}]
I need specifically all of the 'name' value attributes, such as 'Deadpool Gear Bundle', but I'm unsure how. If I try accessing the location info['data']['featured']['name'] location it gives me an error. Also, there could be a different amount of 'name' values every day, so I need a method that returns the attributes of all of them.
So, there's 2 types of objects you need to be aware of.
dict: when you load JSON it's stored as a dictionary object. Dict objects let you access the values through keys, like you're doing here -> info['data']['featured']
list: print(info) is showing that 'info' is a list of things. You can tell by the square brackets [], or just by calling print(type(info)). A list is ordered so to access the name for the first object in your list you would say info[0]['name'].
To get all the objects in your list in a row you can use a for loop:
for x in info:
print(x['name'])
You can name 'x' whatever you want. That loop is just saying " for every object in this list, perform the following action"

How do I turn my JSON into something easier to read?

My Python script connects to an API and gets some JSON.
I've been trying out prettyprint, parse, loads, dumps but I haven't figured them out yet...
Right now, when i do print(request.json()) I get this:
{'info': {'status': 'OK', 'time': {'seconds': 0.050006151199341, 'human': '50 milliseconds'}},
'datalist': {'total': 1, 'count': 1, 'offset': 0, 'limit': 3, 'next': 1, 'hidden': 0, 'loaded': True, 'list': [
{'id': 27862209, 'name': 'Fate/Grand Order', 'package': 'com.xiaomeng.fategrandorder',
'uname': 'komoe-game-fate-go', 'size': 49527668,
'icon': 'http://pool.img.xxxxx.com/msi8/9b58a48638b480c17135a10810374bd6_icon.png',
'graphic': 'http://pool.img.xxxxx.com/msi8/3a240b50ac37a9824b9ac99f1daab8c8_fgraphic_705x345.jpg',
'added': '2017-05-20 10:54:53', 'modified': '2017-05-20 10:54:53', 'updated': '2018-02-12 12:35:51',
'uptype': 'regular', 'store': {'id': 750918, 'name': 'msi8',
'avatar': 'http://pool.img.xxxxx.com/msi8/c61a8cfe9f68bfcfb71ef59b46a8ae5d_ravatar.png',
'appearance': {'theme': 'grey',
'description': '❤️ Welcome To Msi8 Store & My Store Will Mostly Be Specialized in Games With OBB File Extension. I Hope You Find What You Are Looking For Here ❤️'},
'stats': {'apps': 20776, 'subscribers': 96868, 'downloads': 25958359}},
'file': {'vername': '1.14.5', 'vercode': 52, 'md5sum': 'xxxxx', 'filesize': 49527668,
'path': 'http://pool.apk.xxxxx.com/msi8/com-xiaomeng-fategrandorder-52-27862209-32a264b031d6933514970c43dea4191f.apk',
'path_alt': 'http://pool.apk.xxxxx.com/msi8/alt/Y29tLXhpYW9tZW5nLWZhdGVncmFuZG9yZGVyLTUyLTI3ODYyMjA5LTMyYTI2NGIwMzFkNjkzMzUxNDk3MGM0M2RlYTQxOTFm.apk',
'malware': {'rank': 'UNKNOWN'}},
'stats': {'downloads': 432, 'pdownloads': 452, 'rating': {'avg': 0, 'total': 0},
'prating': {'avg': 0, 'total': 0}}, 'has_versions': False, 'obb': None,
'xxxxx': {'advertising': False, 'billing': False}}]}}
But I want it to look like this:
>>> import json
>>> a={"some":"json", "a":{"b":[1,2,3,4]}}
>>> print(json.dumps(a, indent=4, sort_keys=True))
{
"a": {
"b": [
1,
2,
3,
4
]
},
"some": "json"
}

Sort and return all of nested dictionaries based on specified key value

I am trying to re-arrange the contents of a nested dictionaries where it will check the value of a specified key.
dict_entries = {
'entries': {
'AzP746r3Nl': {
'uniqueID': 'AzP746r3Nl',
'index': 2,
'data': {'comment': 'First Plastique Mat.',
'created': '17/01/19 10:18',
'project': 'EMZ',
'name': 'plastique_varA',
'version': '1'},
'name': 'plastique_varA',
'text': 'plastique test',
'thumbnail': '/Desktop/mat/plastique_varA/plastique_varA.jpg',
'type': 'matEntry'
},
'Q2tch2xm6h': {
'uniqueID': 'Q2tch2xm6h',
'index': 0,
'data': {'comment': 'Camino from John Inds.',
'created': '03/01/19 12:08',
'project': 'EMZ',
'name': 'camino_H10a',
'version': '1'},
'name': 'camino_H10a',
'text': 'John Inds : Camino',
'thumbnail': '/Desktop/chips/camino_H10a/camino_H10a.jpg',
'type': 'ChipEntry'
},
'ZeqCFCmHqp': {
'uniqueID': 'ZeqCFCmHqp',
'index': 1,
'data': {'comment': 'Prototype Bleu.',
'created': '03/01/19 14:07',
'project': 'EMZ',
'name': 'bleu_P23y',
'version': '1'},
'name': 'bleu_P23y',
'text': 'Bleu : Prototype',
'thumbnail': '/Desktop/chips/bleu_P23y/bleu_P23y.jpg',
'type': 'ChipEntry'
}
}
}
In my above nested dictionary example, I am trying to check it by the name and created key (2 functions each) and once it has been sorted, the index value will be updated accordingly as well...
Even so, I am able to query for the values of the said key(s):
for item in dict_entries.get('entries').values():
#The key that I am targetting at
tar_key = item['name']
but this is returning me the value of the name key and I am unsure on my next step as I am trying to sort by the value of the name key and capturing + re-arranging all the contents of the nested dictionaries.
This is my desired output (if checking by name):
{'entries': {
'ZeqCFCmHqp': {
'uniqueID': 'ZeqCFCmHqp',
'index': 1,
'data': {'comment': 'Prototype Bleu.',
'created': '03/01/19 14:07',
'project': 'EMZ',
'name': 'bleu_P23y',
'version': '1'},
'name': 'bleu_P23y',
'text': 'Bleu : Prototype',
'thumbnail': '/Desktop/chips/bleu_P23y/bleu_P23y.jpg',
'type': 'ChipEntry'
}
'Q2tch2xm6h': {
'uniqueID': 'Q2tch2xm6h',
'index': 0,
'data': {'comment': 'Camino from John Inds.',
'created': '03/01/19 12:08',
'project': 'EMZ',
'name': 'camino_H10a',
'version': '1'},
'name': 'camino_H10a',
'text': 'John Inds : Camino',
'thumbnail': '/Desktop/chips/camino_H10a/camino_H10a.jpg',
'type': 'ChipEntry'
},
'AzP746r3Nl': {
'uniqueID': 'AzP746r3Nl',
'index': 2,
'data': {'comment': 'First Plastique Mat.',
'created': '17/01/19 10:18',
'project': 'EMZ',
'name': 'plastique_varA',
'version': '1'},
'name': 'plastique_varA',
'text': 'plastique test',
'thumbnail': '/Desktop/mat/plastique_varA/plastique_varA.jpg',
'type': 'matEntry'
}
}
}

python: parse a List within a dictionary [duplicate]

This question already has answers here:
How do I extract all the values of a specific key from a list of dictionaries?
(3 answers)
Closed 4 years ago.
response = {'links': [{'rel': 'self', 'href': 'XXXXXXX'}], 'id': 22, 'attribute_type': 'Number', 'label': 'Type', 'required': True, 'constrained': True, 'order': 2, 'allowed_values': [{'links': [], 'value': 701, 'label': 'Manual', 'order': 1, 'is_default': True, 'is_active': True}, {'links': [], 'value': 702, 'label': 'Automation', 'order': 2, 'is_default': False, 'is_active': True}, {'links': [], 'value': 703, 'label': 'Performance', 'order': 3, 'is_default': False, 'is_active': True}, {'links': [], 'value': 704, 'label': 'Scenario', 'order': 4, 'is_default': False, 'is_active': True}], 'multiple': False, 'data_type': 3, 'searchable': True, 'free_text_search': False, 'search_key': 'type', 'system_field': True, 'original_name': 'Type', 'is_active': True}
so I am able to get the id in the response as such:
for r in response:
if r['label'] == 'Type'
return r['id']
However, I am trying to get 'value' in the 'allowed_values' list in the response.
'allowed_values': [{'links': [], 'value': 701, 'label': 'Manual', 'order': 1, 'is_default': True, 'is_active': True}, {'links': [], 'value': 702, 'label': 'Automation', 'order': 2, 'is_default': False, 'is_active': True}, {'links': [], 'value': 703, 'label': 'Performance', 'order': 3, 'is_default': False, 'is_active': True}, {'links': [], 'value': 704, 'label': 'Scenario', 'order': 4, 'is_default': False, 'is_active': True}]
Is this possible, if so how?
Any help is appreciated. Thanks in advance!
With Anton's help, this is what I ended up using!
if r.get('allowed_values'):
av = r.get('allowed_values')
for av_values in av:
if av_values['label'] == subvalue:
field_value = av_values['value']
return field_value
This is where list comprehensions comes in handy in Python. Hmm, pretty basic though. I will see if I can find a dupe.
values = [i['value'] for i in response['allowed_values']]
print(values) # --> prints[701, 702, 703, 704]

Categories