1

I am creating client, which sent json encoded data to server

Data example:

{ 
"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' }
}

As you can see, there is 2 dict's with 'add' key ant and 3 dict's with 'delete' keys. How its posible?

I am encoding data with:

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

but it encodes only delete3!

So how to create JSON response with same keys? json.dumps maybe can encode dict with same keys, but how to create them in Python? Python dict key is unique...

Thanks for the help!!!

4

1 回答 1

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

这种方法有点脆弱,因为它不能确保action根据 JSON 规则对值进行转义,但只要操作值是不带引号的简单 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"}}
于 2013-08-01T10:28:55.813 回答