I am able to parse json ressponse when there are multiple "nodes" of what I am looking for, but when only one node is returned by the API, I am getting the message "string indices must be integers".
Here is my code in which I am pass in the dictionary after converting it from a string using json.loads():
import requests, requests.auth
import json
import os
def parseSchedule(dict):
i = 0
for item in dict['reservations']['reservation']:
print(item['event_start_dt'])
i += 1
I've simplified the json response to show that this works:
{
"reservations": {
"reservation": [{
"event_start_dt": "2019-11-27T12:40:00-08:00"
}, {
"event_start_dt": "2019-11-27T16:10:00-08:00"
}]
}
}
While this throws the error "string indices must be integers":
{
"reservations": {
"reservation": {
"event_start_dt": "2019-11-26T08:30:00-08:00"
}
}
}
I have researched the .items() in which I attempt the key and value but have been unsuccessful thus far.
You can do it with something like this:
#If it is a list:
if str(type(dict["reservations"]["reservation"])) == "<class 'list'>":
for i in range(len(dict["reservations"]["reservation"])):
print(dict["reservations"]["reservation"][i]["event_start_dt"])
else: #If it is not a list
print(dict['reservations']['reservation']['event_start_dt'])
Related
I have following JSON, where element "Key_with_variable_name" has variable name compared to other keys:
{
"Key1": {
"Key11": {
"Key111": "Value111",
"Key112": "Value112",
"Key113": "Value113",
"Key114": {
"Key1141": {
"Key_with_variable_name": {
"Key114111": {
"Key1141111": "Value1141111",
"Key1141112": "Value1141112",
"Key1141113": "Value1141113"
}
}
}
}
}
}
}
How can I access Key114111 (get its name) which is "under" Key_with_variable_name and then access nested Key1141111 and it's value Value1141111? And can I get value of Key_with_variable_name?
I used json_message = json.loads(jsonObject) and worked on JSON as nested dictionary, but struggled to get down deep past "Key_with_variable_name"
Or maybe it can be done easier working on JSON not on dictionary?
A simple one, but I've just not yet been able to wrap my head around parsing nested lists and json structures in Python...
Here is the raw message I am trying to parse.
{
"Records": [
{
"messageId": "1b9c0952-3fe3-4ab4-a8ae-26bd5d3445f8",
"receiptHandle": "AQEBy40IsvNDy33dOhn4KB8+7apBecWpSuw5OgL9sw/Nf+tM2esLgqmWjGsd4n0oqB",
"body": "{\n \"Type\" : \"Notification\",\n \"MessageId\" : \"dce5c301-029f-55e1-8cee-959b1ad4e500\",\n \"TopicArn\" : \"arn:aws:sns:ap-southeast-2:062497424678:vid\",\n \"Message\" : \"ChiliChallenge.mp4\",\n \"Timestamp\" : \"2020-01-16T07:51:39.807Z\",\n \"SignatureVersion\" : \"1\",\n \"Signature\" : \"oloRF7SzS8ipWQFZieXDQ==\",\n \"SigningCertURL\" : \"https://sns.ap-southeast-2.amazonaws.com/SimpleNotificationService-a.pem\",\n \"UnsubscribeURL\" : \"https://sns.ap-southeast-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:ap-southeast-2:062478:vid\"\n}",
"attributes": {
"ApproximateReceiveCount": "1",
"SentTimestamp": "1579161099897",
"SenderId": "AIDAIY4XD42",
"ApproximateFirstReceiveTimestamp": "1579161099945"
},
"messageAttributes": {},
"md5OfBody": "1f246d643af4ea232d6d4c91f",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:aws:sqs:ap-southeast-2:062497424678:vid",
"awsRegion": "ap-southeast-2"
}
]
}
I am trying to extract the Message in the body section, ending up with a string as "ChiliChallenge.mp4\"
Thanks!
Essentially I just keep getting either TypeError: string indices must be integers or parsing the body but not getting any further into the list without an error.
Here's my attempt:
import json
with open ("event_testing.txt", "r") as myfile:
event=myfile.read().replace('\n', '')
str(event)
event = json.loads(event)
key = event['Records'][0]['body']
print(key)
you can use json.loads to load string
with open ("event_testing.txt", "r") as fp:
event = json.loads(fp.read())
key = json.loads(event['Records'][0]['body'])['Message']
print(key)
'ChiliChallenge.mp4'
Say your message is phrase,
I rebuild your code like:
phrase_2 = phrase["Records"]
print(phrase_2[0]["body"])
Then it works clearly. Because beginning of the Records, it looks like an array so you need to organized it.
I'm trying to scrape a website and get items list from it using python. I parsed the html using BeaufitulSoup and made a JSON file using json.loads(data). The JSON object looks like this:
{ ".1768j8gv7e8__0":{
"context":{
//some info
},
"pathname":"abc",
"showPhoneLoginDialog":false,
"showLoginDialog":false,
"showForgotPasswordDialog":false,
"isMobileMenuExpanded":false,
"showFbLoginEmailDialog":false,
"showRequestProductDialog":false,
"isContinueWithSite":true,
"hideCoreHeader":false,
"hideVerticalMenu":false,
"sequenceSeed":"web-157215950176521",
"theme":"default",
"offerCount":null
},
".1768j8gv7e8.6.2.0.0__6":{
"categories":[
],
"products":{
"count":12,
"items":[
{
//item info
},
{
//item info
},
{
//item info
}
],
"pageSize":50,
"nextSkip":100,
"hasMore":false
},
"featuredProductsForCategory":{
},
"currentCategory":null,
"currentManufacturer":null,
"type":"Search",
"showProductDetail":false,
"updating":false,
"notFound":false
}
}
I need the items list from product section. How can I extract that?
Just do:
products = jsonObject[list(jsonObject.keys())[1]]["products"]["items"]
import json packagee and map every entry to a list of items if it has any:
This solution is more universal, it will check all items in your json and find all the items without hardcoding the index of an element
import json
data = '{"p1": { "pathname":"abc" }, "p2": { "pathname":"abcd", "products": { "items" : [1,2,3]} }}'
# use json package to convert json string to dictionary
jsonData = json.loads(data)
type(jsonData) # dictionary
# use "list comprehension" to iterate over all the items in json file
# itemData['products']["items"] - select items from data
# if "products" in itemData.keys() - check if given item has products
[itemData['products']["items"] for itemId, itemData in jsonData.items() if "products" in itemData.keys()]
Edit: added comments to code
I'll just call the URL of the JSON file you got from BeautifulSoup "response" and then put in a sample key in the items array, like itemId:
import json
json_obj = json.load(response)
array = []
for i in json_obj['items']:
array[i] = i['itemId']
print(array)
I'm kinda new JSON and python and i wish to use the keys and values of JSON to compare it.
I'm getting the JSON from a webpage using requests lib.
Recently, I've done this:
import requests;
URL = 'https://.../update.php';
PARAMS = { 'platform':'0', 'authcode':'code', 'app':'60' };
request = requests.get( url=URL, params=PARAMS );
data = request.json( );
I used this loop to get the keys and values from that json:
for key, value in data.items( ):
print( key, value );
it return JSON part like this:
rescode 0
desc success
config {
"app":"14",
"os":"2",
"version":"6458",
"lang":"zh-CN",
"minimum":"5",
"versionName":"3.16.0-6458",
"md5":"",
"explain":"",
"DiffUpddate":[ ]
}
But in Firefox using pretty print i get different result look like this:
{
"rescode": 0,
"desc": "success",
"config": "{
\n\t\"app\":\"14\",
\n\t\"os\":\"2\",
\n\t\"version\":\"6458\",
\n\t\"lang\":\"zh-CN\",
\n\t\"minimum\":\"5\",
\n\t\"versionName\":\"3.16.0-6458\",
\n\t\"md5\":\"\",
\n\t\"explain\":\"\",
\n\t\"DiffUpddate\":[\n\t\t\n\t]\n
}"
}
What I'm planing to do is:
if data['config']['version'] == '6458':
print('TRUE!');
But everytime i get this error:
TypeError: string indices must be integers
You need to parse the config
json.loads(data['config'])['version']
Or edit the PHP to return an associative array rather than a string for the config object
I have the next JSON in JS
var intervalos= {
"operandos":[{
"extremoInferior":$(edit_numvar).context.value,
"extremoSuperior":$(edit_numvar2).context.value
},
{
"extremoInferior":$(edit_numvar3).context.value,
"extremoSuperior":$(edit_numvar4).context.value
}]
};
and I did parsed_input = json.loads(self.intervalos)
but now I don't know how to access to my dict. I tried with
intervalos[operandos][extremoInferior])
but it returns an error.
Could you help me for accessing to any element of my dict?
After deserializing JSON to Python object you could simply access to elements. For example:
parsed_input = json.loads(self.intervalos)
extremo_inferior_0 = parsed_input['operandos'][0]['extremoInferior']
Please try this code:
import simplejson as json
json_string = """{"operandos":[
{
"extremoInferior":"somevalue1",
"extremoSuperior":"somevalue2"
},
{
"extremoInferior":"somevalue3",
"extremoSuperior":"somevalue4"
}]
}"""
json_data = json.loads(json_string)
print "Complete Dict: "
print json_data
print "operandos -> extremoInferior: "
print json_data['operandos'][0]['extremoInferior']
intervalos['operandos'][0]['extremoInferior']
or
intervalos['operandos'][1]['extremoInferior']
intervalos['operandos'] is defined as an array of two of these objects.