0

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?

simplycoding
  • 2,770
  • 9
  • 46
  • 91
  • Ah thanks. Would you recommend using something like `str.replace` to replace the inner single quotes to double quotes? – simplycoding Jun 09 '16 at 23:46
  • I would just switch the your use of single quotes for double quotes. It's less confusing for anyone reading your code. –  Jun 09 '16 at 23:50
  • 1
    You shouldn't try to create JSON by hand, there are a number of details that you're not likely to get right. Use a library function that creates JSON from a data structure, such as `json.dumps()`. – Barmar Jun 09 '16 at 23:53
  • Where did your single quoted list come from? – Alex Hall Jun 09 '16 at 23:54
  • It came from Yelp's data set. – simplycoding Jun 10 '16 at 00:12

1 Answers1

1

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/

  • Thanks. The data actually isn't JSON format, but I was able to just replace the single quotes with double quotes on the SQL side before using the function. Not the best way, but all I need is something that works. – simplycoding Jun 10 '16 at 00:13