55211

Parsing JSON Github API - Django 1.8

Question:

I have this in my views.py:

def profile(request): parsedData = [] if request.method == 'POST': username = request.POST.get('user') req = requests.get('https://api.github.com/users/' + username + '/repos') jsonList = [] jsonList.append(req.json()) userData = {} data = ['owner'] for data in jsonList: userData['html_url'] = data['owner'][0]['html_url'] userData['created_at'] = data['created_at'] userData['updated_at'] = data['updated_at'] userData['forks_count'] = data['forks_count'] parsedData.append(userData) return render(request, 'app/profile.html', {'data': parsedData})

This throws me:

TypeError at /app/profile/ list indices must be integers, not str

This is an example JSON returned by /repos on Github:

{ "id": 77549474, "name": "acp", "full_name": "kkoci/acp", "owner": { "login": "kkoci", "id": 3047897, "avatar_url": "https://avatars0.githubusercontent.com/u/3047897?v=4", "gravatar_id": "", "url": "https://api.github.com/users/kkoci", "html_url": "https://github.com/kkoci", "followers_url": "https://api.github.com/users/kkoci/followers", "following_url": "https://api.github.com/users/kkoci/following{/other_user}", "gists_url": "https://api.github.com/users/kkoci/gists{/gist_id}", "starred_url": "https://api.github.com/users/kkoci/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/kkoci/subscriptions", "organizations_url": "https://api.github.com/users/kkoci/orgs", "repos_url": "https://api.github.com/users/kkoci/repos", "events_url": "https://api.github.com/users/kkoci/events{/privacy}", "received_events_url": "https://api.github.com/users/kkoci/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/kkoci/acp", "description": null, "fork": true, "url": "https://api.github.com/repos/kkoci/acp", "forks_url": "https://api.github.com/repos/kkoci/acp/forks", "keys_url": "https://api.github.com/repos/kkoci/acp/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/kkoci/acp/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/kkoci/acp/teams", "hooks_url": "https://api.github.com/repos/kkoci/acp/hooks", "issue_events_url": "https://api.github.com/repos/kkoci/acp/issues/events{/number}", "events_url": "https://api.github.com/repos/kkoci/acp/events", "assignees_url": "https://api.github.com/repos/kkoci/acp/assignees{/user}", "branches_url": "https://api.github.com/repos/kkoci/acp/branches{/branch}", "tags_url": "https://api.github.com/repos/kkoci/acp/tags", "blobs_url": "https://api.github.com/repos/kkoci/acp/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/kkoci/acp/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/kkoci/acp/git/refs{/sha}", "trees_url": "https://api.github.com/repos/kkoci/acp/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/kkoci/acp/statuses/{sha}", "languages_url": "https://api.github.com/repos/kkoci/acp/languages", "stargazers_url": "https://api.github.com/repos/kkoci/acp/stargazers", "contributors_url": "https://api.github.com/repos/kkoci/acp/contributors", "subscribers_url": "https://api.github.com/repos/kkoci/acp/subscribers", "subscription_url": "https://api.github.com/repos/kkoci/acp/subscription", "commits_url": "https://api.github.com/repos/kkoci/acp/commits{/sha}", "git_commits_url": "https://api.github.com/repos/kkoci/acp/git/commits{/sha}", "comments_url": "https://api.github.com/repos/kkoci/acp/comments{/number}", "issue_comment_url": "https://api.github.com/repos/kkoci/acp/issues/comments{/number}", "contents_url": "https://api.github.com/repos/kkoci/acp/contents/{+path}", "compare_url": "https://api.github.com/repos/kkoci/acp/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/kkoci/acp/merges", "archive_url": "https://api.github.com/repos/kkoci/acp/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/kkoci/acp/downloads", "issues_url": "https://api.github.com/repos/kkoci/acp/issues{/number}", "pulls_url": "https://api.github.com/repos/kkoci/acp/pulls{/number}", "milestones_url": "https://api.github.com/repos/kkoci/acp/milestones{/number}", "notifications_url": "https://api.github.com/repos/kkoci/acp/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/kkoci/acp/labels{/name}", "releases_url": "https://api.github.com/repos/kkoci/acp/releases{/id}", "deployments_url": "https://api.github.com/repos/kkoci/acp/deployments", "created_at": "2016-12-28T17:23:45Z", "updated_at": "2016-12-28T17:23:46Z", "pushed_at": "2016-12-28T13:00:52Z", "git_url": "git://github.com/kkoci/acp.git", "ssh_url": "git@github.com:kkoci/acp.git", "clone_url": "https://github.com/kkoci/acp.git", "svn_url": "https://github.com/kkoci/acp", "homepage": null, "size": 113, "stargazers_count": 0, "watchers_count": 0, "language": "Python", "has_issues": false, "has_projects": true, "has_downloads": true, "has_wiki": true, "has_pages": false, "forks_count": 0, "mirror_url": null, "archived": false, "open_issues_count": 0, "license": null, "forks": 0, "open_issues": 0, "watchers": 0, "default_branch": "8.0" },

I've tried in many ways but the error persists, any ideas?

<strong>EDIT</strong>

The error comes at this line userData['html_url'] = data['owner'][0]['html_url'] but also on the rest of them, it's just an example of two ways I've been trying this. The error persists.

Answer1:

The response from github is already a list, so the first element in your jsonList is a list and this is the reason for the exception.

Change to:

jsonList=req.json()

and it should work

Answer2:

The problem is that you're appending the response to a list. Then the response only contain one JSON object.

Thus, you don't even have to loop it. Just assign the values directly.

data = req.json() userData = {} # Copy values right away userData['html_url'] = data['owner'][0]['html_url'] userData['created_at'] = data['created_at'] userData['updated_at'] = data['updated_at'] userData['forks_count'] = data['forks_count']

Then in your response, if the client is NOT expecting a list, no need to append the userData to a list type. Just pass it directly as:

return render(request, 'app/profile.html', {'data': userData})

Answer3:

data = ['owner'] means data is a list contains one string owner but not means it is a dictionary contains one key owner(correct one should be something like data={"owner": None}).

So when you access it like data["owner"], you are trying to use it like a dictionary, but it is a list.

And that's why you get error: list indices must be integers, not str.

Recommend

  • Github API get the last commit for every repository with a search term response
  • smack for android fails when using proguard
  • publish_stream message visibility to everyone
  • Get username of logged in user in os via browser
  • Search Facebook by first name with Koala
  • Making public posts via Facebook App?
  • Cut the background to expose the layer below
  • Regarding starting the threads on a condition
  • Unable to send e-mail through Java
  • NUnit 3.0 TestCase const custom object arguments
  • Undefined references when compiling gSOAP client
  • how does System.Web.HttpRequest::PathInfo work?
  • IE11 throwing “SCRIPT1014: invalid character” where all other browsers work
  • Can someone please explain to me in the most layman terms how to use EventArgs?
  • Reading a file into a multidimensional array
  • How to remove a SwiftyJSON element?
  • RxJava debounce by arbitrary value
  • pyodbc doesn't report sql server error
  • NSScanner Loop Question
  • Display java JPanel in a JFrame
  • how to display data from 1st point on words on y axis for line chart in d3.js
  • Row Count Is Returning the incorrect number using RaptureXML
  • how to adjust image in a panel in Java swing?
  • Encrypt data by using a public key in c# and decrypt data by using a private key in php
  • How to make a tree having multiple type of nodes and each node can have multiple child nodes in java
  • WinForms: two way TextBox problem
  • VB.net deserialize, JSON Conversion from type 'Dictionary(Of String,Object)' to type '
  • Linker errors when using intrinsic function via function pointer
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • How do I configure my settings file to work with unit tests?
  • Turn off referential integrity in Derby? is it possible?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • LevelDB C iterator
  • Authorize attributes not working in MVC 4
  • Busy indicator not showing up in wpf window [duplicate]
  • Binding checkboxes to object values in AngularJs
  • How can i traverse a binary tree from right to left in java?
  • Python/Django TangoWithDjango Models and Databases
  • Net Present Value in Excel for Grouped Recurring CF