Python json使用相同的键编码(solr)

时间:2013-08-01 10:23:41

标签: python json encoding solr

我正在创建客户端,它将json编码数据发送到服务器

数据示例:

{ 
"add": {
  "doc": {
    "id": "DOC1",
    "my_boosted_field": {
      "boost": 2.3,
      "value": "test"
    },
    "my_multivalued_field": [ "aaa", "bbb" ]
  }
},
"add": {
  "commitWithin": 5000,
  "overwrite": false,uniqueKey */
  "boost": 3.45,
  "doc": {
    "f1": "v1",
    "f1": "v2"
  }
},

"commit": {},
"optimize": { "waitFlush":false, "waitSearcher":false },

"delete": { "id":"ID" },
"delete": { "query":"QUERY" }
"delete": { "query":"QUERY", 'commitWithin':'500' }
}

正如你所看到的,有2个带有'add'键蚂蚁的dict和带有'delete'键的3个dict。 它的可行性如何?

我用以下代码编码数据:

data = {}
data['delete'] = delete1
data['delete'] = delete2
data['delete'] = delete3
print json.dumps(data)

但它只编码delete3!

那么如何使用相同的密钥创建JSON响应? json.dumps可能可以使用相同的键编码dict,但是如何在Python中创建它们? Python dict键是唯一的......

感谢您的帮助!!!

1 个答案:

答案 0 :(得分:2)

Python词典具有唯一键。 JSON对象应该具有唯一的名称,但是您找到的SOLR示例违反了该名称。引自JSON RFC

  

对象中的名称应该是唯一的。

因为在Python词典中,名称 唯一,所以无法使用标准json库来生成您显示的输出。

如果您需要特定输出,则必须滚动自己的编码器。我生成一个(action, dictionary)对元组列表,然后使用json库对字典进行编码,然后在最后一步使用字符串模板:

data = []
data.append(('delete', delete1))
data.append(('delete', delete2))
data.append(('delete', delete3))

output = '{%s}' % ',\n'.join(['"{}": {}'.format(action, json.dumps(dictionary)) for action, dictionary in data])

这种方法是 little 脆弱,因为它不能确保{J}规则对action值进行转义,但只要动作值是简单的ASCII字符串而没有引号它工作得很好。您始终可以将编码添加到unicode_escape并手动转义任何"个字符。

演示:

>>> import json
>>> delete1 = { "id":"ID" }
>>> delete2 = { "query":"QUERY" }
>>> delete3 = { "query":"QUERY", 'commitWithin':'500' }
>>> data = []
>>> data.append(('delete', delete1))
>>> data.append(('delete', delete2))
>>> data.append(('delete', delete3))
>>> '{%s}' % ',\n'.join(['"{}": {}'.format(action, json.dumps(dictionary)) for action, dictionary in data])
'{"delete": {"id": "ID"},\n"delete": {"query": "QUERY"},\n"delete": {"query": "QUERY", "commitWithin": "500"}}'
>>> print '{%s}' % ',\n'.join(['"{}": {}'.format(action, json.dumps(dictionary)) for action, dictionary in data])
{"delete": {"id": "ID"},
"delete": {"query": "QUERY"},
"delete": {"query": "QUERY", "commitWithin": "500"}}