I've searched and there's a similar problem here but the solution states to fix the json. I really cant fix the json produced as its from a REST API.
{
"__metadata": {
"uri": "http://website:6405/biprws/v1/cmsquery?page=1&pagesize=50"
},
"first": {
"__deferred": {
"uri": "http://website:6405/biprws/v1/cmsquery?page=1&pagesize=50"
}
},
"last": {
"__deferred": {
"uri": "http://website:6405/biprws/v1/cmsquery?page=1&pagesize=50"
}
},
"entries": [
{
"SI_ID": 31543,
"SI_NAME": "Some Client",
"SI_PARENTID": 31414,
"SI_PATH": {
"SI_FOLDER_NAME1": "COR OPS",
"SI_FOLDER_ID1": 31414,
"SI_FOLDER_OBTYPE1": 1,
"SI_FOLDER_NAME2": "CLIENT",
"SI_FOLDER_ID2": 28178,
"SI_FOLDER_OBTYPE2": 1,
"SI_NUM_FOLDERS": 2
}
}
]
}
I need to be able to get the folder names from SI_PATH, but that is where I am having issues. I can access "entries" fine as the whole json is considered as a dict, but the problem is after. If I get "entries", its just a list with a len of 1
import json
data = json.load(open('file.json'))
print(type(data))
print(data['entries])
print(type(data['entries']))
Sample output below:
<class 'dict'>
<class 'list'>
[{'SI_ID': 31543, 'SI_NAME': 'Some Client', 'SI_PARENTID': 31414, 'SI_PATH': {'SI_FOLDER_NAME1': 'COR OPS', 'SI_FOLDER_ID1': 31414, 'SI_FOLDER_OBTYPE1': 1, 'SI_FOLDER_NAME2': 'CLIENT', 'SI_FOLDER_ID2': 28178, 'SI_FOLDER_OBTYPE2': 1, 'SI_NUM_FOLDERS': 2}}]
I can use pandas to put the 'entries' onto a DataFrame and pull in the SI_PATH values, but not sure how to access each of them.
f = pd.DataFrame(data['entries'])
print(f['SI_PATH'].values)
Output of this:
[{'SI_FOLDER_NAME1': 'COR OPS', 'SI_FOLDER_ID1': 31414, 'SI_FOLDER_OBTYPE1': 1, 'SI_FOLDER_NAME2': 'CLIENT', 'SI_FOLDER_ID2': 28178, 'SI_FOLDER_OBTYPE2': 1, 'SI_NUM_FOLDERS': 2}]
But unsure as to how to access the items individual from this point. If possible, really want to stick with just importing json.
Since there is only one item in the list that is data['entries']:
print(data['entries'][0]['SI_ID'])
Prints:
31543
since it is a list of dict, why not
for items in data['entries']:
print(items.get("SI_ID"))
Related
I'm using an API call to retrieve JSON data, the response to the get request is formatted like this:
data: JSON representation of resource requested
linked: an object containing additional entities
meta: miscellaneous information based on the endpoint.
When I do:
DictData = response.json()
json_formatted_str = json.dumps(DictData, indent = 2)
print(json_formatted_str)
I get all three sections (data, linked, meta):
{
"meta": {},
"linked": {}
"data": [
{
"date_on_hold": null,
"cc": [],
"labels": [
"Sales/Licensing"
],
"agent": 8,
"person": 210
}
]
And when I do:
DictData = response.json()
json_formatted_str = json.dumps(DictData['data'], indent = 2)
print(json_formatted_str)
I specifically get the data section:
[
{
"date_on_hold": null,
"cc": [],
"labels": [
"Sales/Licensing"
],
"agent": 8,
"person": 210
}
]
How would I go about specifically extracting the "person" tuple in the "data" section? In this example, I would want to print out '210'.
I believe I'm getting a list of objects, and I'm currently printing out the "data" object, but how would I print/extract the "person" variable in the "data" object?
Use
json_dict["data"][0]["person"]
Since DictData['data'] is a list of 1 element, to get value of a single person you can do:
DictData['data'][0]['person']
In case you need to iterate over the data list you can do:
for element in DictData['data']:
print(element['person'])
I have to prepare JSON files to send using POST, but I have faced the following format to handle:
offer {
"location":
{
"city": "Kharkov",
"address": "street"
}
"dates": [
{
"start_date": "2018-10-10 14:00",
"end_date": "2018-11-11 14:00"
}]
}
Before it, to set the Value for the city field I used the following implementation:
offer['location']['city'] = "Kharkov"
But now I can't figure out how to add the value to the key start_date since the dictionary is inside the list.
'dates' is a list. Use index to access the key inside.
Ex:
offer['dates'][0]["start_date"] = "NewDate"
print(offer)
Output:
{'dates': [{'start_date': 'NewDate', 'end_date': '2018-11-11 14:00'}], 'location': {'city': 'Kharkov', 'address': 'street'}}
Can some one tell me what I am doing wrong ?I am Getting this error..
went through the earlier post of similar error. couldn't able to understand..
import json
import re
import requests
import subprocess
res = requests.get('https://api.tempura1.com/api/1.0/recipes', auth=('12345','123'), headers={'App-Key': 'some key'})
data = res.text
extracted_recipes = []
for recipe in data['recipes']:
extracted_recipes.append({
'name': recipe['name'],
'status': recipe['status']
})
print extracted_recipes
TypeError: string indices must be integers
data contains the below
{
"recipes": {
"47635": {
"name": "Desitnation Search",
"status": "SUCCESSFUL",
"kitchen": "eu",
"active": "YES",
"created_at": 1501672231,
"interval": 5,
"use_legacy_notifications": false
},
"65568": {
"name": "Validation",
"status": "SUCCESSFUL",
"kitchen": "us-west",
"active": "YES",
"created_at": 1522583593,
"interval": 5,
"use_legacy_notifications": false
},
"47437": {
"name": "Gateday",
"status": "SUCCESSFUL",
"kitchen": "us-west",
"active": "YES",
"created_at": 1501411588,
"interval": 10,
"use_legacy_notifications": false
}
},
"counts": {
"total": 3,
"limited": 3,
"filtered": 3
}
}
You are not converting the text to json. Try
data = json.loads(res.text)
or
data = res.json()
Apart from that, you probably need to change the for loop to loop over the values instead of the keys. Change it to something the following
for recipe in data['recipes'].values()
There are two problems with your code, which you could have found out by yourself by doing a very minimal amount of debugging.
The first problem is that you don't parse the response contents from json to a native Python object. Here:
data = res.text
data is a string (json formatted, but still a string). You need to parse it to turn it into it's python representation (in this case a dict). You can do it using the stdlib's json.loads() (general solution) or, since you're using python-requests, just by calling the Response.json() method:
data = res.json()
Then you have this:
for recipe in data['recipes']:
# ...
Now that we have turned data into a proper dict, we can access the data['recipes'] subdict, but iterating directly over a dict actually iterates over the keys, not the values, so in your above for loop recipe will be a string ( "47635", "65568" etc). If you want to iterate over the values, you have to ask for it explicitly:
for recipe in data['recipes'].values():
# now `recipe` is the dict you expected
I'm constructing a dictionary with Python to use with a SOAP API.
My SOAP API takes an input like this:
<dataArray>
<AccountingYearData>
<Handle>
<Year>string</Year>
</Handle>
<Year>string</Year>
<FromDate>dateTime</FromDate>
<ToDate>dateTime</ToDate>
<IsClosed>boolean</IsClosed>
</AccountingYearData>
<AccountingYearData>
<Handle>
<Year>string</Year>
</Handle>
<Year>string</Year>
<FromDate>dateTime</FromDate>
<ToDate>dateTime</ToDate>
<IsClosed>boolean</IsClosed>
</AccountingYearData>
</dataArray>
Se this for the full string
https://api.e-conomic.com/secure/api1/EconomicWebService.asmx?op=AccountingYear_CreateFromDataArray
Notice how the field appears multiple times.
How can I create a Python dict with this data?
If I do this:
data = {
'dataArray':{
'AccountingYearData':{
'Handle':{'Year':'2017'},
'Year':'2017',
'FromDate':'2017-01-01',
'ToDate':'2017-12-31',
'IsClosed':'False'
},
'AccountingYearData':{
'Handle':{'Year':'2017'},
'Year':'2017',
'FromDate':'2017-01-01',
'ToDate':'2017-12-31',
'IsClosed':'False'
}
}
}
I get:
>>> type (data)
<type 'dict'>
>>> data {
'dataArray': {
'AccountingYearData': {
'IsClosed': 'False',
'FromDate': '2017-01-01',
'Handle': {'Year': '2017'},
'ToDate': '2017-12-31',
'Year': '2017'
}
}
}
It's as expected I think, but now what I need.
Well, the answer seems obvious and is even hinted by the "dataArray" name: if you have a list of items, then you want to use a list to store them:
data = {
'dataArray':[
{
'AccountingYearData':{
'Handle':{'Year':'2017'},
'Year':'2017',
'FromDate':'2017-01-01',
'ToDate':'2017-12-31',
'IsClosed':'False'
},
},
{
'AccountingYearData':{
'Handle':{'Year':'2017'},
'Year':'2017',
'FromDate':'2017-01-01',
'ToDate':'2017-12-31',
'IsClosed':'False'
},
},
]
}
i'm having trouble with a simple question.
a = {
"apiVersion": "2.1",
"data": {
"startIndex": 1,
"items": [{
"id": "YVA3UoZM0zU",
"title": "Trailer - Lisbela eo Prisioneiro"
}]
}
}
i don't know how to get the info id.
this is a string.
so, i tried to make this
import simplejson as json
>>> type(js)
<type 'dict'>
js = json.loads(a)
print js['data'{'items'[{'id'}]}]
>>> syntax error
this syntax is invalid, how could I get this info? it's supposed to be easy. where I'm making wrong?
Try:
js['data']['items'][0]['id']
It would appear that there may be multiple items in this structure. If you'd like to extract all item ids as a list, the following will do it:
[item['id'] for item in js['data']['items']]