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'])
Related
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.
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', '')]
{
"type": "Data",
"version": "1.0",
"box": {
"identifier": "abcdef",
"serial": "12345678"
},
"payload": {
"Type": "EL",
"Version": "1",
"Result": "Successful",
"Reference": null,
"Box": {
"Identifier": "abcdef",
"Serial": "12345678"
},
"Configuration": {
"EL": "1"
},
"vent": [
{
"ventType": "Arm",
"Timestamp": "2020-03-18T12:17:04+10:00",
"Parameters": [
{
"Name": "Arm",
"Value": "LT"
},
{
"Name": "Status",
"Value": "LD"
}
]
},
{
"ventType": "Arm",
"Timestamp": "2020-03-18T12:17:24+10:00",
"Parameters": [
{
"Name": "Arm",
"Value": "LT"
},
{
"Name": "Status",
"Value": "LD"
}
]
},
{
"EventType": "TimeUpdateCompleted",
"Timestamp": "2020-03-18T02:23:21.2979668Z",
"Parameters": [
{
"Name": "ActualAdjustment",
"Value": "PT0S"
},
{
"Name": "CorrectionOffset",
"Value": "PT0S"
},
{
"Name": "Latency",
"Value": "PT0.2423996S"
}
]
}
]
}
}
If you're looking to transfer information from a JSON file to a CSV, then you can use the following code to read in a JSON file into a dictionary in Python:
import json
with open('data.txt') as json_file:
data_dict = json.load(json_file)
You could then convert this dictionary into a list with either data_dict.items() or data_dict.values().
Then you just need to write this list to a CSV file which you can easily do by just looping through the list.
{
'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..
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()}