Getting elements of a JSON string python - python

Well, this is my JSON string:
[{"id":1,"name":"firstname lastname","longitude":"45.567856","latitude":"345.2334"},
{"id":2,"name":"firstname1 lastname1","longitude":"45.567856","latitude":"345.2334"}]
This is my code where I'd like to split it:
api = 'http://localhost:8080/serviceBackend/employees'
json_data = requests.get(api).json()
print(json_data)
employeeName = json_data['']['name']
print(employeeName)
If I run this code I'm getting this error TypeError: list indices must be integers or slices, not str
The result should be
firstname lastname, firstname1 lastname1

You can try This:
api = 'http://localhost:8080/serviceBackend/employees'
json_data = requests.get(api).json()
print(json_data)
employeeName = ', '.join([data.get('name') for data in json_data])
print(employeeName)

try this
>>> a = [{"id":1,"name":"firstname lastname","longitude":"45.567856","latitude":"345.2334"},
... {"id":2,"name":"firstname1 lastname1","longitude":"45.567856","latitude":"345.2334"}]
>>> ', '.join([i.get('name') for i in a])
'firstname lastname, firstname1 lastname1'
>>>

you're trying to get variables from loop statement.
you can move by loop with such code:
names = []
for item in json_data:
# get name key from item in type of dictionary and put it in names list
names.apend(item.get('name'))
or using list comprehension, a bit sophisticated but more 'elegant':
names = [item.get('name') for item in json_data]
print(names)
So your code looks like this:
api = 'http://localhost:8080/serviceBackend/employees'
json_data = requests.get(api).json()
print(json_data)
employeeName = [item.get('name') for item in json_data]
print(employeeName)

Related

parse github api.. getting string indices must be integers error

I need to loop through commits and get name, date, and messages info from
GitHub API.
https://api.github.com/repos/droptable461/Project-Project-Management/commits
I have many different things but I keep getting stuck at string indices must be integers error:
def git():
#name , date , message
#https://api.github.com/repos/droptable461/Project-Project-Management/commits
#commit { author { name and date
#commit { message
#with urlopen('https://api.github.com/repos/droptable461/Project Project-Management/commits') as response:
#source = response.read()
#data = json.loads(source)
#state = []
#for state in data['committer']:
#state.append(state['name'])
#print(state)
link = 'https://api.github.com/repos/droptable461/Project-Project-Management/events'
r = requests.get('https://api.github.com/repos/droptable461/Project-Project-Management/commits')
#print(r)
#one = r['commit']
#print(one)
for item in r.json():
for c in item['commit']['committer']:
print(c['name'],c['date'])
return 'suc'
Need to get person who did the commit, date and their message.
item['commit']['committer'] is a dictionary object, and therefore the line:
for c in item['commit']['committer']: is transiting dictionary keys.
Since you are calling [] on a string (the dictionary key), you are getting the error.
Instead that code should look more like:
def git():
link = 'https://api.github.com/repos/droptable461/Project-Project-Management/events'
r = requests.get('https://api.github.com/repos/droptable461/Project-Project-Management/commits')
for item in r.json():
for key in item['commit']['committer']:
print(item['commit']['committer']['name'])
print(item['commit']['committer']['date'])
print(item['commit']['message'])
return 'suc'

How do I add a variable to a JSON list in Python?

I have a JSON file that looks likes this:
{ "users":"John, admin"}
What I want is to be able to add a string into the "users" title.
So, basically, I want to allow users to input a new username and add it to this list. Take the following Python code:
newUserInfo = input("Enter a new username: ")
And then say I input "Michael"
Then the JSON file should look like this:
{ "users":"John, admin, Michael"}
I've tried the following:
with open(userFile, "a") as userobj:
newUserInfo = json.dump(allUserInfo["users": newUserInfo], userobj)
And It returns an error. Is there an easy way to do this?
Thanks in advance.
Append the name to the string:
import json
s = '''{"users":"John, admin"}'''
data = json.loads(s)
newUserInfo = input("Enter a new username: ")
data['users'] += ', ' + newUserInfo
s2 = json.dumps(data)
print(s2)
Output:
{"users": "John, admin, Michael"}
But a more natural way to use JSON would be represent the names in a list:
import json
s = '''{"users":["John","admin"]}'''
data = json.loads(s)
newUserInfo = input("Enter a new username: ")
data['users'].append(newUserInfo)
s2 = json.dumps(data)
print(s2)
Output:
{"users": ["John", "admin", "Michael"]}

How should I connect dictionary's user_id & model's user_id?

I wanna parse excel& make dictionary and connect the model(User) which has same user_id of dictionary.
Now dictionary is
dict_data = {'user_id': 1,'nationarity': America, 'dormitory':'A', 'group': 3}
Models in views.py is
user = User(user_id=rows[1],name_id=rows[2],age=rows[3],employee=rows[4])
If I wanna add dictionary's data to model,I should write like
for data in dict_data:
User(**data)
but how should I connect dictionary's user_id& models' one?What should I write it?
Now I wrote like
#coding:utf-8
from django.shortcuts import render
import xlrd
from app.models import User
book3 = xlrd.open_workbook('./data/XXX.xlsx')
sheet3 = book3.sheet_by_index(0)
headers = sheet3.row_values(0)
large_item = None
dicts = {}
for row_index in range(sheet3.nrows):
rows3 = sheet3.row_values(row_index)
large_item = rows3[1] or large_item
# Create dict with headers and row values
row_data = {}
for idx_col, value in enumerate(rows3):
header_value = headers[idx_col]
# Avoid to add empty column. A column in your example
if header_value:
row_data[headers[idx_col]] = value
# Add row_data to your data_dict with
dicts[row_index] = row_data
for data in dicts:
user1 = User.objects.filer(user_id = data['user_id']).exists()
if user1:
user1.__dict__.update(**dicts)
user1.save()
When I run this code,
AttributeError: 'Manager' object has no attribute 'filer'
user1 = User.objects.filer(user_id = data['user_id']).exists()
How should I fix this?
for data in dict_datas:
user = User.object.filter(user_id = data['user_id']).exists()
if user:
user.__dict__.update(**dict_data)
user.save()
dict_data you posted is a dict,you shouldn't iterate it like a list.
I guess your dict_data is a list of dict, so:
for data in dict_datas:
user = User.objects.get(user_id=data['user_id'])
user.name_id = data['**']
...
user.save()
First, fetch the user object with user_id in your xecel&dict, then change the value, and save it.

How to reference a json array element by name using Python?

In this json array:
json_string=[{"Id": "report","Value": "3001"},{"Id": "user","Value": "user123"}]
How can I get back user123 if I pass in user
When I try to do this:
content = json.loads(json_string)
content['user']
I get an error that says you have to use integer to reference an element.
I am brand new to Python.
Thanks!
content is a list so you should get the element by index first:
>>> content[1]['Value']
'user123'
>>> for d in content:
... if 'user' in d.values():
... print d['Value']
'user123'
Assuming user is always mapped to Id:
>>> for d in content:
... if d['Id'] == 'user':
... print d['Value']
One liner:
>>> [d['Value'] for d in content if d['Id'] == 'user'][0]
'user123'
Assuming you want to focus on the first occurrence of an element in the list with a given field (e.g. 'Id') with a certain value (e.g. 'user'):
def look_for(string, field, val):
return next((el['Value'] for el in string if el[field] == val))
json_string = [{"Id": "report","Value": "3001"}, {"Id": "user","Value": "user123"}]
found_val = look_for(json_string, 'Id', 'user')
produces
'user123'
Obviously, also the output field can become a parameter instead of being hardcoded to Value

list indices must be integers, not str 6

I am very new to python and am really struggling to find a solution to this issue.
I just don't understand why I need to include only integers in my list when I though they are supposed to support multiple data types.
I've got a very simple field entry system for an account registration and I just can't add the items into a list.
Any help would be greatly appreciated. I've have included my code and the message I receive.
useraccounts = {}
group = []
forename = input('Forename: ')
surname = input('Surname: ')
DOB = input('DOB: ')
stu_class = input('Class: ')
group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class
group.append(user accounts)
This is the error message:
Traceback (most recent call last):
File "/Users/admin/Documents/Homework/Computing/testing/testing.py", line 11, in <module>
group['forename'] = forename
TypeError: list indices must be integers, not str
It looks like you want group to be a dict, and useraccounts to be a list. You have them backwards, as well as the append:
useraccounts = [] # <-- list
group = {} # <-- dict
forename = input('Forename: ')
surname = input('Surname: ')
DOB = input('DOB: ')
stu_class = input('Class: ')
group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class
useraccounts.append(group) # <-- reversed. this will append group to useraccounts
As written, you were trying to append useraccuonts, an empty list, to group, a dict which has no append method
What you want is a dictionary:
group = {}
group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class
In your original code useraccounts stays an empty dict that you just append to the list. If you wanted to add group to useraccounts:
useraccounts['key'] = group
group is a list, it cannot take string indices. It looks like you wanted to use a dictionary instead:
useraccounts = []
group = {}
group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class
useraccounts.append(group)
Note that you probably wanted useraccounts to be the list here; your code tried to call .append() on the group object..
or inline the keys and values directly into the dictionary definition:
useraccounts.append({
'forename': forename,
'surname': surname,
'dob']: DOB,
'class': stu_class})

Categories

Resources