Skip to content Skip to sidebar Skip to footer

JSON To Arrays Python

I searched on internet, without success, a way to set JSON infos into arrays, with a JSON file like: { '_links': {}, 'chatter_count': 3, 'chatters': { 'moderators': ['nightbot', 'm

Solution 1:

Here is the good way to convert a Json file to python variable:

import json

data = None
with open('/path/to/your/file/here.json', 'r') as fd:
    data = json.loads(fd.read())
print data["chatters"]["moderators"]

Here what the code is doing:

The code below open the file from the given path, read all the content and convert it into a dict() object which is a python default type (https://docs.python.org/2/library/stdtypes.html#dict).

You can also parse json directly from a string:

import json

json_str = '{ "_links": {}, "chatter_count": 3, "chatters": { "moderators": ["nightbot", "mistercraft"], "staff": [], "admins": [], "global_mods": [], "viewers": [] } }'
data = json.loads(json_str)
print data["chatters"]["moderators"]

Solution 2:

You should use the built-in json library for this. The json.loads method will return a dict object in your case.

>>> import json

>>> json_data = json.loads('{ "_links": {}, "chatter_count": 3, "chatters": { "moderators": ["nightbot", "mistercraft"], "staff": [], "admins": [], "global_mods": [], "viewers": [] } }')
>>> json_data
{u'chatters': {u'moderators': [u'nightbot', u'mistercraft'], u'global_mods': [], u'admins': [], u'viewers': [], u'staff': []}, u'_links': {}, u'chatter_count': 3}

>>> json_data['chatters']['moderators']
[u'nightbot', u'mistercraft']

If you are dealing with a json file instead of json string, then you should use the json.load method instead of json.loads, like below -

with open('path/to/json/file') as json_file:
    json_data = json.load(json_file)

Solution 3:

from json import loads
array = loads('{ "_links": {}, "chatter_count": 3, "chatters": { "moderators": ["nightbot", "mistercraft"], "staff": [], "admins": [], "global_mods": [], "viewers": [] } }')

Then you can access "moderators" like this:

array["chatters"]["moderators"]

Solution 4:

Take a look at the JSON library: https://docs.python.org/3.6/library/json.html

To parse your JSON:

import json
json.loads(json_text)

From your example, this would return a dict.

To access your moderators:

import json

chatter=json.loads(json_text)
moderators = chatter.get('chatters',{}).get('moderators')

moderators will now be the array ["nightbot", "mistercraft"]


Post a Comment for "JSON To Arrays Python"