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.
Related
I have a JSON String like this:
{
"Sommersprossen": {
"count": 5,
"lastSeenTime": 1586959168567
},
"inkognito": {
"count": 7,
"lastSeenTime": 1586901586361
},
"Marienkäfer": {
"count": 7,
"lastSeenTime": 1586958264090,
"difficulty": 0.8902439024390244,
"difficultyWeight": 82
},
"Zaun": {
"count": 8,
"lastSeenTime": 1586958848320
},
Now I want to print something like this: Sommersprossen, inkognito, Marienkäfer, Zaun.
But I don't know how to...
My existing Python code is:
url = "https://skribbliohints.github.io/German.json"
response = urllib.request.urlopen(url)
data = json.loads(response.read())
But the problem is I cant find a way to print the objects names.
A json is essentially just a dictionary. You can access it like any other python dictionary.
url = "https://skribbliohints.github.io/German.json"
response = urllib.request.urlopen(url)
data = json.loads(response.read())
roots = list(data.keys())
You can treat this json output as dictionary and print its Keys, for this exapmle you can simply perform it with:
data.keys()
Output:
dict_keys(['Sommersprossen', 'inkognito', 'Marienkäfer', 'Zaun'])
It’s a dict, so you can do:
“, “.join(data.keys())
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'])
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
Why does this code give a KeyError?
output_format = """
{
"File": "{filename}",
"Success": {success},
"ErrorMessage": "{error_msg}",
"LogIdentifier": "{log_identifier}"
}
"""
print output_format.format(filename='My_file_name',
success=True,
error_msg='',
log_identifier='123')
Error message:
KeyError: ' "File"'
You need to double the outer braces; otherwise Python thinks { "File".. is a reference too:
output_format = '{{ "File": "{filename}", "Success": {success}, "ErrorMessage": "{error_msg}", "LogIdentifier": "{log_identifier}" }}'
Result:
>>> print output_format.format(filename='My_file_name',
... success=True,
... error_msg='',
... log_identifier='123')
{ "File": "My_file_name", "Success": True, "ErrorMessage": "", "LogIdentifier": "123" }
If, indicentally, you are producing JSON output, you'd be better off using the json module:
>>> import json
>>> print json.dumps({'File': 'My_file_name',
... 'Success': True,
... 'ErrorMessage': '',
... 'LogIdentifier': '123'})
{"LogIdentifier": "123", "ErrorMessage": "", "Success": true, "File": "My_file_name"}
Note the lowercase true in the output, as required by the JSON standard.
As mentioned by Tudor in a comment to another answer, the Template class was the solution that worked best for me. I'm dealing with nested dictionaries or list of dictionaries and handling those were not as straightforward.
Using Template though the solution is quite simple.
I start with a dictionary that is converted into a string. I then replace all instances of { with ${ which is the Template identifier to substitute a placeholder.
The key point of getting this to work is using the Template method safe_substitute. It will replace all valid placeholders like ${user_id} but ignore any invalid ones that are part of the dictionary structure, like ${'name': 'John', ....
After the substitution is done I remove any leftovers $ and convert the string back to a dictionary.
In the code bellow, resolve_placeholders returns a dictionary where each key matches a placeholder in the payload string and the value is substituted by the Template class.
from string import Template
.
.
.
payload = json.dumps(payload)
payload = payload.replace('{', '${')
replace_values = self.resolve_placeholders(payload)
if replace_values:
string_template = Template(payload)
payload = string_template.safe_substitute(replace_values)
payload = payload.replace('${', '{')
payload = json.loads(payload)
To extend on Martijn Pieters answer and comment:
According to MArtijn' comment, escaping the {..} pairs that are not placeholders is they way to go with nested dictionaries. I haven't succeded in doing that, so I suggest the following method.
For nested dictionaries I tried doubling up on any { and } of the nested dictionaries.
a='{{"names":{{"a":"{name}"}}}}'
a.format(name=123) output:
output: '{"names":{"a":"123"}}'
But this makes using format to change values inside a json string, a over-complex method, so I use a twist on the format command.
I replace ${param_name} in a json string. For example:
My predefined JSON looks like this:
my_json_dict = {
'parameter': [
{
'name': 'product',
'value': '${product}'
},
{
'name': 'suites',
'value': '${suites}'
},
{
'name': 'markers',
'value': '${markers}'
}
]
}
I provide this dictionary as values to replace instead of the parameters
parameters = {
'product': 'spam',
'suites': 'ham',
'markers': 'eggs'
}
And use this code to do the replacment
json_str = json.dumps(my_json_dict)
for parameter_name, parameter_value in parameters.iteritems():
parameter_name = '${'+parameter_name+'}'
json_str = json_str.replace(parameter_name, parameter_value)
json_dict = json.loads(json_str)