How can I reach nested in nested dictionary values? - python

{
'data':[
"firstName": "Jane",
"lastName": "Doe",
"hobbies": ["running", "sky diving", "singing"],
"age": 35,
"children": [
{
"firstName": "Sandy,
"age": 6
"values":[
{
'value' :908
}
]
},
{
"firstName": "Alice",
"age": 7
"values":[
{
'value' :0123
}
]
}
{
"firstName": "Dany",
"age": 8
"values":[
{
'value' :0193
}
]
}
]
}
**This is my json file .I try to reach first names ,values and age each block and write database.**I tried a lot of things and I cant run ..
.
.
results=r.json()
for k in results['data']:
for k1 in k['children']:
data={"firstname":k1['firstName']....?Values?)
How can I reach each block values and every values in one json format ?

I believe your example is coming from the web. But as Alberto Poljak and fizzybear pointed your json format was somewhat broken.
I corrected it here and there and in this format it should work:
{
"data":
{
"firstName": "Jane",
"lastName": "Doe",
"hobbies": ["running", "sky diving", "singing"],
"age": 35,
"children": [
{
"firstName": "Sandy",
"age": 6,
"values":[
{
"value" :908
}
]
},
{
"firstName": "Alice",
"age": 7,
"values":[
{
"value" :123
}
]
},
{
"firstName": "Dany",
"age": 8,
"values":[
{
"value" :193
}
]
}
]
}
}
If you save the above in a file "family.json" then this sample code should be working fine:
import json
with open('family.json') as json_file:
data = json.load(json_file)
p = data['data']['children']
for r in p:
print('First name: %s' % r['firstName'])
print('Age: %d' % r['age'])
print('')
For quick review of json files you can use e.g. https://codebeautify.org/jsonviewer, where you can validate it or see its content in a tree structure etc..

Related

Comparison of same property in different objects-JSON schema

Please see below json schema:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"firstname": {
"type": "string"
},
"lastname": {
"type": "string"
},
"post_sql": {
"type": "object",
"properties": {
"datasets": {
"type": "array",
"items": {
"type": "object",
"properties": {
"firstname": {
"type": "string"
},
"lastname": {
"type": "string"
},
"access": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
}
}
}
}
I want to compare firstname and lastname of first object which is at top with firstname and lastname which is inside post_sql->datasets if they are same then all accesses to that user ["insert","update","delete"] else only["select"] access for different user.
sample data:
{
"registration": {
"firstname": "john",
"lastname": "dharman",
"post_sql": {
"datasets": [
{
"firstname": "john",
"lastname": "dharman",
"access": [
"select","insert","update","delete"
]
},
{
"firstname": "jenny",
"lastname": "shein",
"access": [
"select","insert","update","delete"
]
}
]
}
}
}
in above example
"firstname": "john",
"lastname": "dharman"
are same in first object and in post_sql->datasets:
"post_sql": {
"datasets": [
{
"firstname": "john",
"lastname": "dharman",
"access": [
"select","insert","update","delete"
]
},
so john should get all accesses but if firstname and last name are not same(like jenny in above data) then we need to give only ["select"] like in above example second object have one more dataset with:
{
"firstname": "jenny",
"lastname": "shein",
"access": [
"select","insert","update","delete"
]
}
so I want such if-else in my json schema where it will check firstname and lastname with second object and based on that if both are same then all access array should be given to that user
[
"select","insert","update","delete"
]
else only
["select"]
I tried to put if else in datasets but some how it did not work please help in this. We just need if->else-> then statements but its just this json schema contains a bit nested objects in one schema.

load an object if a key contains a specific value (month)

Is there a way to load only an object which contains specific key value from json?
The steps what I have done:
response = requests.get(URL, headers={'token': TOKEN}, verify=False)
meta_json = json.loads(response.content)
meta_json looks like this:
{
"count": 264428,
"data": [
{
"calculation_date": "2020-04-09T12:33:05.814107",
"name": "Felix",
"age": 12
},
{
"calculation_date": "2020-03-09T12:33:05.814107",
"name": "Max",
"age": 18
},
{
"calculation_date": "2020-04-09T12:33:15.814207",
"name": "John",
"age": 25
}
],
"links": {
"first": "random",
"last": "second"
}
}
But I would like to see only the month April, and meta_json should look like this:
{
"count": 264428,
"data": [
{
"calculation_date": "2020-04-09T12:33:05.814107",
"name": "Felix",
"age": 12
},
{
"calculation_date": "2020-04-09T12:33:15.814207",
"name": "John",
"age": 25
}
],
"links": {
"first": "random",
"last": "second"
}
}
How to do this?
You could filter your result after the load, like below:
meta_json['data']=[i for i in meta_json['data'] if '-04-' in i.get('calculation_date', '')]

Exchange of 2 json data values which has different keys

I want to exchange 2 json data's value. But keys of these datas are different from each other. I don't know how can I exchange data value between them.
sample json1: A
{
"contact_person":"Mahmut Kapur",
"contact_people": [
{
"email": "m#gmail.com",
"last_name": "Kapur"
}
],
"addresses": [
{
"city": "istanbul",
"country": "CA",
"first_name": "Mahmut",
"street1": "adres 1",
"zipcode": "34678",
"id": "5f61f72b8348230004f149fd"
}
]
"created_at": "2020-09-16T07:29:47.244-04:00",
"updated_at": "2020-09-16T07:32:50.567-04:00",
}
sample json2: B
The values in this example are: Represents the keys in the A json.
{
"Customer":{
"DisplayName":"contact_person",
"PrimaryEmailAddr":{
"Address":"contact_people/email"
},
"FamilyName":"contact_people/last_name",
"BillAddr":{
"City":"addresses/city",
"CountrySubDivisionCode":"addresses/country",
"Line1":"addresses/street1",
"PostalCode":"addresses/zipcode",
"Id":"addresses/id"
},
"GivenName":"addresses/first_name",
"MetaData":{
"CreateTime":"created_at",
"LastUpdatedTime":"updated_at"
}
}
}
The outcome needs to be:
{
"Customer":{
"DisplayName":"Mahmut Kapur",
"PrimaryEmailAddr":{
"Address":"m#gmail.com"
},
"FamilyName":"Kapur",
"BillAddr":{
"City":"istanbul",
"CountrySubDivisionCode":"CA",
"Line1":"adres 1",
"PostalCode":"34678",
"Id":"5f61f72b8348230004f149fd"
},
"GivenName":"Mahmut",
"MetaData":{
"CreateTime":"2020-09-16T07:29:47.244-04:00",
"LastUpdatedTime":"2020-09-16T07:32:50.567-04:00"
}
}
}
So the important thing here is to match the keys. I hope I was able to explain my problem.
This code can do the work for you. I dont know if someone can make this code shorter for you. It basically searches for dict and list till the leaf level and acts accordingly.
a={
"contact_person":"Mahmut Kapur",
"contact_people": [
{
"email": "m#gmail.com",
"last_name": "Kapur"
}
],
"addresses": [
{
"city": "istanbul",
"country": "CA",
"first_name": "Mahmut",
"street1": "adres 1",
"zipcode": "34678",
"id": "5f61f72b8348230004f149fd"
}
],
"created_at": "2020-09-16T07:29:47.244-04:00",
"updated_at": "2020-09-16T07:32:50.567-04:00",
}
b={
"Customer":{
"DisplayName":"contact_person",
"PrimaryEmailAddr":{
"Address":"contact_people/email"
},
"FamilyName":"contact_people/last_name",
"BillAddr":{
"City":"addresses/city",
"CountrySubDivisionCode":"addresses/country",
"Line1":"addresses/street1",
"PostalCode":"addresses/zipcode",
"Id":"addresses/id"
},
"GivenName":"addresses/first_name",
"MetaData":{
"CreateTime":"created_at",
"LastUpdatedTime":"updated_at"
}
}
}
c={}
for keys in b:
if isinstance(b[keys], dict):
for items in b[keys]:
if isinstance(b[keys][items], dict):
for leaf in b[keys][items]:
if "/" in b[keys][items][leaf]:
getter=b[keys][items][leaf].split("/")
b[keys][items][leaf]=a[getter[0]][0][getter[1]]
else:
b[keys][items][leaf]=a[b[keys][items][leaf]]
else:
if "/" in b[keys][items]:
getter=b[keys][items].split("/")
b[keys][items]=a[getter[0]][0][getter[1]]
else:
b[keys][items]=a[b[keys][items]]
else:
if "/" in b[keys]:
getter=b[keys].split("/")
b[keys]=a[getter[0]][0][getter[1]]
else:
b[keys]=a[b[keys]]
print(json.dumps(b,indent=4))

Reorder and return the whole of nested dictionary

I am trying to retain the whole contents of a nested dictionary but only with its contents reordered..
This is an example of my nested dictionaries (pardon the long example..) -
{
"pages": {
"rotatingTest": {
"elements": {
"apvfafwkbnjn2bjt": {
"name": "animRot_tilt40_v001",
"data": {
"description": "tilt testing",
"project": "TEST",
"created": "26/11/18 16:32",
},
"type": "AnimWidget",
"uid": "apvfafwkbnjn2bjt"
},
"p0pkje1hjcc9jukq": {
"name": "poseRot_positionD_v003",
"data": {
"description": "posing test for positionD",
"created": "10/01/18 14:16",
"project": "TEST",
},
"type": "PosedWidget",
"uid": "p0pkje1hjcc9jukq"
},
"k1gzzc5uy1ynqtnj": {
"name": "animRot_positionH_v001",
"data": {
"description": "rotational posing test for positionH",
"created": "13/06/18 14:19",
"project": "TEST",
},
"type": "AnimWidget",
"uid": "k1gzzc5uy1ynqtnj"
}
}
},
"panningTest": {
"elements": {
"7lyuri8g8u5ctwsa": {
"name": "posePan_positionZ_v001",
"data": {
"description": "panning test for posZ",
"created": "04/10/18 12:43",
"project": "TEST",
},
"type": "PosedWidget",
"uid": "7lyuri8g8u5ctwsa"
}
}
},
"zoomingTest": {
"elements": {
"prtn0i6ehudhz475": {
"name": "posZoom_positionH_v010",
"data": {
"description": "zoom test",
"created": "11/10/18 12:42",
"project": "TEST",
},
"type": "PosedWidget",
"uid": "prtn0i6ehudhz475"
}
}
}
},
"page_order": [
"rotatingTest",
"zoomingTest",
"panningTest"
]
}
and this is my code:
for k1, v1 in test_dict.get('pages', {}).items():
return (sorted(v1.get('elements').items(), key=lambda (k2,v2): v2['data']['created']))
In the code, keys such as the page_order, pages etc are missing...
Or if there is/ are any commands where it will enables me to retain the 'whole' of the dictionary?
Appreciate in advance for any advice.
If you're using Python 3.7, a dict will preserve insert order. Otherwise, you need to use an OrderedDict.Additionally, you need to convert the date string to a date to get the correct sort order:
from datetime import datetime
def sortedPage(d):
return {k: {'elements': dict(sorted(list(v['elements'].items()), key=lambda tuple: datetime.strptime(tuple[1]['data']['created'], '%d/%m/%y %H:%M')))} for k,v in d.items()}
output = {k: sortedPage(v) if k == 'pages' else v for k,v in input.items()}

python json(how to read mulpite id in comple

I have json file i what to read all the values
data=""" {"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
{
"maps":[
{"id":"apple","iscategorical":"0"},
{"id":"ball","iscategorical":"0"}
],
"mask":{"id1":"aaaaa"},
"mask":{"id1":"bbb"},
"mask":{"id1":"cccccc"},
"om_points":"value",
"parameters":
{"id":"valore"}
}"""
out = json.loads(data)
how to get all values
firstname
lastname
mask.id1
map.id
output:
[(firstname_vaues,lastname_values,mask.id1,map.id)
(firstname_vaues,lastname_values,mask.id1,map.id) ......]
please help me
First thing, there are two json objects in your data string. So you cannot use json.loads(data). You can seperate them by a charcter like ";" . Then split the string and use json.loads on each of them.Use following code.
import json
data=""" {
"employees": [{
"firstName": "John",
"lastName": "Doe"
}, {
"firstName": "Anna",
"lastName": "Smith"
}, {
"firstName": "Peter",
"lastName": "Jones"
}]
};{
"maps": [{
"id": "apple",
"iscategorical": "0"
}, {
"id": "ball",
"iscategorical": "0"
}],
"mask": {
"id1": "aaaaa"
},
"mask": {
"id1": "bbb"
},
"mask": {
"id1": "cccccc"
},
"om_points": "value",
"parameters": {
"id": "valore"
}
}"""
splitdata = data.split(';')
datatop = json.loads(splitdata[0])
databottom = json.loads(splitdata[1])
Then you can access required fields as follows
print(datatop['employees'][0]['firstName'])
print(datatop['employees'][0]['lastName'])
print(databottom['mask']['id1'])
print(databottom['maps'][0]['id'])

Categories

Resources