Saturday, 17 August 2013

JSON to Python Dictionary

JSON to Python Dictionary

{"servers":[{"server_id":"1","server_name":"Derron","address":"198.74.57.185","port":"9160","populatio
n":"163","status":"open","guild_id":"0","tournament":"0","happy_hour":"0"},{"server_id":"2","server_name":"Carina","address":"198.74.57.185","port":"9161","population":"12","status":"open","guild_id":"0","tournament":"0","happy_hour":"0"},{"server_id":"3","server_name":"Grayan","address":"198.74.57.185","port":"9162","population":"0","status":"open","guild_id":"0","tournament":"0","happy_hour":"0"},{"server_id":"4","server_name":"Fitz","address":"198.74.57.185","port":"9163","population":"9","status":"open","guild_id":"0","tournament":"0","happy_hour":"0"},{"server_id":"5","server_name":"Loki","address":"198.74.57.185","port":"9164","population":"8","status":"open","guild_id":"0","tournament":"0","happy_hour":"0"},{"server_id":"6","server_name":"Promie","address":"198.74.57.185","port":"9165","population":"2","status":"open","guild_id":"0","tournament":"0","happy_hour":"0"},{"server_id":"7","server_name":"Morgana","address":"198.74.57.185","port":"9166","population":"0","stat
us":"open","guild_id":"0","tournament":"0","happy_hour":"0"},{"server_id":"8","server_name":"Andres","address":"198.74.57.185","port":"9167","population":"0","status":"open","guild_id":"0","tournament":"0","happy_hour":"0"},{"server_id":"10","server_name":"Tournament","address":"198.74.57.185","port":"9168","population":"0","status":"open","guild_id":"0","tournament":"1","happy_hour":"0"}]}
There is the JSON file. I want to split them up into each
category("server_id", "server_name", etc.)
I have tried tons of things but I dont even know how close I'm getting.
I want to get it like this:
import json
posts = ["{'author':'John Smith', 'translator':'Jane Doe'}"]
authors = []
translators = []
for post in posts:
double_quotes_post = post.replace("'", '"')
json_data = json.loads(double_quotes_post)
author = json_data.get('author', None)
translator = json_data.get('translator', None)
if author: authors.append(author)
if translator: translators.append(translator)

No comments:

Post a Comment