user3707451
user3707451

Reputation: 21

Python Array JSON (dumps)

Google App Engine, Python27

I am trying to encode a python array of strings to a JSON string to send to the client. I created a working solution, which requires me to manually create a string version of the array and call dumps on it from python, but I don't believe it should be necessary:

def get_json(cls):
  name_query = cls.query()
  array_string = "["
  index = 1
  for name in name_query:
      array_string += '"' + name.key.id() + '"'
      if index < name_query.count():
          array_string += ", "
      index += 1
  array_string += "]"
  return json.dumps(array_string)

>> "[\"Billy\", \"Bob\"]"

For my second attempt, I tried calling "dumps" on a python array, which I believe should be a working solution; instead, I have to call dumps twice:

# (bad output)
def get_json(cls):
  name_query = cls.query()
  name_array = []        
  for name in name_query:
      name_array.append(name.key.id())
  return json.dumps(name_array)

  >> ["Billy", "Bob"]

# (working output)
def get_json(cls):
  name_query = cls.query()
  name_array = []        
  for name in name_query:
      name_array.append(name.key.id())
  return json.dumps(json.dumps(name_array)))

  >> "[\"Billy\", \"Bob\"]"

Even though I have a working solution, is there a better way and why does calling dumps on a python array not give the correct output?

Upvotes: 2

Views: 8218

Answers (1)

dano
dano

Reputation: 94891

The first function is working fine; it's outputting a valid JSON string. I think the confusion for you is that it's not surrounded in double-quotes, but that's just because you're printing the output of the function.

It's returning a string containing a JSON list, not a Python list object:

>>> def get_json():
...  x = ["Billy", "Bob"]
...  return json.dumps(x)
... 
>>> print get_json()
["Billy", "Bob"]
>>> print repr(get_json())
'["Billy", "Bob"]'  # It's a string, not a list
>>> type(get_json())
<type 'str'>  # See? Type is str

When you call json.dumps twice, you're just wrapping the Python string returned by the first json.dumps call in double-quotes, and the double-quotes that were inside the array get escaped, because they're embedded in one big JSON string now, instead of being used as quotes around JSON strings inside a JSON array.

>>> print repr(json.dumps(get_json()))
'"[\\"Billy\\", \\"Bob\\"]"'

Upvotes: 2

Related Questions