gobob gobob - 3 months ago 14
Python Question

two keys with the same name "$or"

This is a PARSE REST API question. I need to send some json to query the parse server using the Parse REST API. The json needs to contain two keys with the same name "$or". The first key/value is ignored and the second key/value is used by the server. I realise dictionaries can't have two keys with the same name. I've spent a fair bit of time looking at the documentation but its unclear how multiple $or can be done. Is there any way around this?

import json,httplib,urllib
connection = httplib.HTTPSConnection('api.parse.com', 443)
params = urllib.urlencode({"where":json.dumps({
"gender": "male",
"$or": [
{
"brand": "nike"
},
{
"brand": "adidas"
}
],
"$or": [
{
"prim_color": "red"
},
{
"prim_color": "blue"
}
]
})})
connection.connect()
connection.request('GET', '/1/classes/My_Class?%s' % params, '', {
"X-Parse-Application-Id": "API-ID",
"X-Parse-REST-API-Key": "REST-KEY"
})
result = json.loads(connection.getresponse().read())
print result

Answer

As shown in the doc, $or accept an array with one or more conditions to optionally fulfill:

import json,httplib,urllib
connection = httplib.HTTPSConnection('api.parse.com', 443)
params = urllib.urlencode({"where":json.dumps({
       "gender": "male",
       "$or": [
         {
           "brand": "nike"
         },
         {
           "brand": "adidas"
         },
         {
           "prim_color": "red"
         },
         {
           "prim_color": "blue"
         }
       ]
     })})
connection.connect()
connection.request('GET', '/1/classes/Player?%s' % params, '', {
       "X-Parse-Application-Id": "${APPLICATION_ID}",
       "X-Parse-REST-API-Key": "${REST_API_KEY}"
     })
result = json.loads(connection.getresponse().read())
print result

Edit: Ok, you want to have at least one brand/color from your lists.
Sadly their parser is pretty bad and you cannot do complex query (In your case even doing an $and with $or inside...). Where's operators cannot be embedded into others (and only $or is implemented so far).

Anyway you can use $in to use as an $or condition ...

import json,httplib,urllib
connection = httplib.HTTPSConnection('api.parse.com', 443)
params = urllib.urlencode({"where":json.dumps({
       "gender": "male",
       "brand": { "$in": ["nike", "adidas"] }
       "prim_color": { "$in": ["red", "blue"] }
     })})
connection.connect()
connection.request('GET', '/1/classes/Player?%s' % params, '', {
       "X-Parse-Application-Id": "${APPLICATION_ID}",
       "X-Parse-REST-API-Key": "${REST_API_KEY}"
     })
result = json.loads(connection.getresponse().read())
print result