simplycoding simplycoding - 6 months ago 11
JSON Question

What format does data input have to be for Python's json.loads?

I'm trying to use

json.loads
to parse data in a Redshift database table. I've stripped out the function to test in a Python script and am having trouble understanding what's happening.

The code I'm using is:

import json
j="'['Bars', 'American (Traditional)', 'Nightlife', 'Restaurants']'"

def trythis(item, reverse):
if not j:
return '1'
try:
arr = json.loads(j)
except ValueError:
return '2'
if not ascending:
arr = sorted(arr, reverse=True)
else:
arr = sorted(arr)
return json.dumps(arr)

print trythis(j, True)


And this is returning
2
.

I've tried changing the input variable to
j="['Bars', 'American (Traditional)', 'Nightlife', 'Restaurants']"
but that hasn't worked. What format does my entry value need to be?

Answer

Your input string j is not valid JSON. JSON doesn't allow the use of single quotes (') to denote string values.

Try switching the quotes: '["Bars", "American (Traditional)", "Nightlife", "Restaurants"]'

The JSON specification is an excellent resource for determining if your input is valid JSON. You can find it here: http://www.json.org/