Python - get a LIST value from field in JSON

Viewed 164

I have a JSON file containing three fields: 2 are strings and third one is field containing a list of values.

{   "STREAM": "stream",
    "BASIS_STREAM": "basis",
    "PATHS": "[/opt/path1,/opt/path2]"
}

Now I load that JSON

with open('/pathToJsonFile.json', 'r') as f:
    data = json.load(f)

Now I want to get those values.

stream=str(data["STREAM"])
basis=str(data["BASIS_STREAM"])
paths=data["BASE_PATHS"]

The issue is that paths is also threated as String, although I have to use it as a list. I am converting with str function other fields because of the Unicode. Code must be in python2. Thanks a lot!

2 Answers

Say you have a file called data.json with the following contents:

{
   "STREAM": "stream",
   "BASIS_STREAM": "basis",
   "PATHS": "[/opt/path1,/opt/path2]"
}

Maybe you could use str.split after calling json.load:

with open('data.json', 'r') as f:
    data = json.load(f)
print 'data = %s' % data
stream = str(data['STREAM'])
basis = str(data['BASIS_STREAM'])
paths = [str(u_s) for u_s in data['PATHS'][1:-1].split(',')]
print 'stream = %s' % stream
print 'basis = %s' % basis
print 'paths = %s' % paths

Output:

data = {u'PATHS': u'[/opt/path1,/opt/path2]', u'BASIS_STREAM': u'basis', u'STREAM': u'stream'}
stream = stream
basis = basis
paths = ['/opt/path1', '/opt/path2']

Your /opt/path1 and /opt/path2 should be in a quotation marks to be converted in a list. If your PATHS always have a similar template such as "[/XXX,/YYY,/ZZZ,/TTT,/KKK]" the following code should also help. I have converted your data as "['/XXX','/YYY','/ZZZ','/TTT','/KKK']" so that it can be easily converted to a list using ast library. Please see the code as following:

import json
import ast

with open("text_text.json") as f:
    data = json.load(f)

print(data["PATHS"]) # Your data

for i in data["PATHS"]:
    if i == "[":
        data["PATHS"] = data["PATHS"].replace("[", "['")
    elif i == ",":
        data["PATHS"] = data["PATHS"].replace(",/", "','/")
    elif i == "]":
        data["PATHS"] = data["PATHS"].replace("]", "']")
    #print(data["PATHS"])

print(type(data["PATHS"]))
print(data["PATHS"]) #converted to a data which can be converted to a list.
data_paths = ast.literal_eval(data["PATHS"]) # ast is used to convert str to list. 

print(data_paths) # 'list' data
print(type(data_paths))

See the output of the code:

enter image description here

It should also work if your PATH has more data as following:

enter image description here

Related