The error message is correct.
key = json.loads(response['password'])
print(key[0]),
The format of json is string. You need to convert the string of a json object to python dict before you can access it.
i.e.: loads(string) before info[key]
key = json.loads(response)['password']
print(key[0])
Answer from Cireo on Stack OverflowThe error message is correct.
key = json.loads(response['password'])
print(key[0]),
The format of json is string. You need to convert the string of a json object to python dict before you can access it.
i.e.: loads(string) before info[key]
key = json.loads(response)['password']
print(key[0])
Usually the json will be a string and you will try and deserialise it into a object graph (which in python are typically are made up of maps and arrays).
so assuming your response is actually a string (eg that was retrieved from a HTTP request/endpoint) then you deserialise it with json.loads (the function is basically load from string), then you've got a map with a 'password' key, that is an array, so grab the first element from it.
import json
resp = '{ "password": [ "Ensure that this field has atleast 5 and atmost 50 characters" ] }'
print json.loads(resp)['password'][0]
python - Accessing JSON elements - Stack Overflow
Python Parse JSON array - Stack Overflow
Python accessing element inside array inside json - Stack Overflow
How to Access unlabeled JSON array elements in Python? - Stack Overflow
import json
weather = urllib2.urlopen('url')
wjson = weather.read()
wjdata = json.loads(wjson)
print wjdata['data']['current_condition'][0]['temp_C']
What you get from the url is a json string. And your can't parse it with index directly.
You should convert it to a dict by json.loads and then you can parse it with index.
Instead of using .read() to intermediately save it to memory and then read it to json, allow json to load it directly from the file:
wjdata = json.load(urllib2.urlopen('url'))
Here's an alternative solution using requests:
import requests
wjdata = requests.get('url').json()
print wjdata['data']['current_condition'][0]['temp_C']
In your for loop statement, Each item in json_array is a dictionary and the dictionary does not have a key store_details. So I modified the program a little bit
import json
input_file = open ('stores-small.json')
json_array = json.load(input_file)
store_list = []
for item in json_array:
store_details = {"name":None, "city":None}
store_details['name'] = item['name']
store_details['city'] = item['city']
store_list.append(store_details)
print(store_list)
If you arrived at this question simply looking for a way to read a json file into memory, then use the built-in json module.
with open(file_path, 'r') as f:
data = json.load(f)
If you have a json string in memory that needs to be parsed, use json.loads() instead:
data = json.loads(my_json_string)
Either way, now data is converted into a Python data structure (list/dictionary) that may be (deeply) nested and you'll need Python methods to manipulate it.
If you arrived here looking for ways to get values under several keys as in the OP, then the question is about looping over a Python data structure. For a not-so-deeply-nested data structure, the most readable (and possibly the fastest) way is a list / dict comprehension. For example, for the requirement in the OP, a list comprehension does the job.
store_list = [{'name': item['name'], 'city': item['city']} for item in json_array]
# [{'name': 'Mall of America', 'city': 'Bloomington'}, {'name': 'Tempe Marketplace', 'city': 'Tempe'}]
Other types of common data manipulation:
For a nested list where each sub-list is a list of items in the
json_array.store_list = [[item['name'], item['city']] for item in json_array] # [['Mall of America', 'Bloomington'], ['Tempe Marketplace', 'Tempe']]For a dictionary of lists where each key-value pair is a category-values in the
json_array.store_data = {'name': [], 'city': []} for item in json_array: store_data['name'].append(item['name']) store_data['city'].append(item['city']) # {'name': ['Mall of America', 'Tempe Marketplace'], 'city': ['Bloomington', 'Tempe']}For a "transposed" nested list where each sub-list is a "category" in
json_array.store_list = list(store_data.values()) # [['Mall of America', 'Tempe Marketplace'], ['Bloomington', 'Tempe']]
Use json.load for reading a file or json.loads for a string.
data_dict = json.loads(your_data)
print(data_dict["Data"]["classic"][0]["app"])
Use json loads to parse a json string and json dumps for stringifying the json to a json string
Here in your case you will need json loads
input = {
"Data": {
"Name": "myname",
"AccountName": "test",
"classic": [
{
"cName": "mycname",
"tags": ["tag1", "tag2"],
"Version": "1.14.10",
"app": "myapp"
}
]
}
}
parsed_input = json.loads(input)
output = parsed_input["Data"]["classic"][0]["app"]
print(output)
JSON is a string format. To turn it into Python data structures, you "load" it:
data = response.read()
dataStream = json.loads(data)
Now dataStream is a list of dictionaries. The first of it is dataStream[0], and the 'faceId' element of it is dataStream[0]['faceId'].
1) Accessing a json array obtained as a response for a GET request.
[{"symbol":"EURUSD","bid":1.13859,"ask":1.13911,"price":1.13885,"timestamp":1541215930}]
json_data = json.loads(response.text)
bid = json_data[0]['bid']
ask = json_data[0]['ask']
price = json_data[0]['price']
timestamp = json_data[0]['timestamp']
2) Accessing a simple json without having an array as follows.
{"rates":{"EURUSD":{"rate":1.138789,"timestamp":1541224588014}},"code":200}
json_data = json.loads(response.text)
result = json_data['rates']['EURUSD']
rate = json_data['rates']['EURUSD']['rate']
timestamp = json_data['rates']['EURUSD']['timestamp']
code = json_data['code']
Take a look at the json module. More specifically the 'Decoding JSON:' section.
import json
import requests
response = requests.get() # api call
users = json.loads(response.text)
for user in users:
print(user['id'])
You can try like below to get the values from json response:
import json
content=[{
"username": "admin",
"first_name": "",
"last_name": "",
"roles": "system_admin system_user",
"locale": "en",
"delete_at": 0,
"update_at": 1511335509393,
"create_at": 1511335500662,
"auth_service": "",
"email": "adminuser@cognizant.com",
"auth_data": "",
"position": "",
"nickname": "",
"id": "pbjds5wmsp8cxr993nmc6ozodh"
}, {
"username": "chatops",
"first_name": "",
"last_name": "",
"roles": "system_user",
"locale": "en",
"delete_at": 0,
"update_at": 1511335743479,
"create_at": 1511335743393,
"auth_service": "",
"email": "chatops@cognizant.com",
"auth_data": "",
"position": "",
"nickname": "",
"id": "akxdddp5p7fjirxq7whhntq1nr"
}]
for item in content:
print("Name: {}\nEmail: {}\nID: {}\n".format(item['username'],item['email'],item['id']))
Output:
Name: admin
Email: adminuser@cognizant.com
ID: pbjds5wmsp8cxr993nmc6ozodh
Name: chatops
Email: chatops@cognizant.com
ID: akxdddp5p7fjirxq7whhntq1nr