Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays Python数组JSON(转储)_Arrays_Json_Google App Engine_Python 2.7 - Fatal编程技术网

Arrays Python数组JSON(转储)

Arrays Python数组JSON(转储),arrays,json,google-app-engine,python-2.7,Arrays,Json,Google App Engine,Python 2.7,谷歌应用引擎,Python27 我正在尝试将一个python字符串数组编码为一个JSON字符串,以发送给客户端。我创建了一个有效的解决方案,它要求我手动创建数组的字符串版本,并从python中对其调用转储,但我认为这不是必需的: def get_json(cls): name_query = cls.query() array_string = "[" index = 1 for name in name_query: array_string += '"' + na

谷歌应用引擎,Python27

我正在尝试将一个python字符串数组编码为一个JSON字符串,以发送给客户端。我创建了一个有效的解决方案,它要求我手动创建数组的字符串版本,并从python中对其调用转储,但我认为这不是必需的:

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\"]"

尽管我有一个可行的解决方案,但还有更好的方法吗?为什么在python数组上调用转储不能给出正确的输出?

第一个函数运行良好;它正在输出一个有效的JSON字符串。我认为让您感到困惑的是,它没有被双引号包围,但这只是因为您正在打印函数的输出

它返回一个包含JSON列表的字符串,而不是Python
list
对象:

>>> 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

除非数组中的引号被转义,否则我会一直收到一个错误,如果应该,repr不会为我转义引号。@user370741您收到了什么错误?在问题中编辑完整的回溯/调用代码。另外,
repr
并不是用来转义引号的,它只是向您显示对象的可打印表示。我用它来说明您得到的是一个
str
,而不是
列表
。json.dumps会转义我生成的字符串上的引号,或者如果我在python数组中使用了两次对dumps的调用。我认为必须对引号进行转义才能使其成为有效的json。如果通过将内容类型设置为“application/json”,将json.dumps(name_array)作为json写入响应,我没有从ajax中获得任何输出或超时错误
>>> 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
>>> print repr(json.dumps(get_json()))
'"[\\"Billy\\", \\"Bob\\"]"'