I am breaking my head for the lat 5 hours to find out how to create programmatically in Python a dictionary with specific values inside which I take from a list. It sounds very easy (and it must be) but I am totally lost among errors with double quotes, string values and escaping characters. Any help would be really most appreciated. At least to understand what the heck I am doing wrong:
I will try to be as more detailed as possible. What I want to do is to create programmatically this:
checkNode = {'statements':[
{"statement":"MATCH (n:RealNode { id: "1" }) SET n.telecomType = 'P', n.buildingType= 'c' RETURN n"},
{"statement":"MATCH (n:RealNode { id: "2" }) SET n.telecomType = 'P', n.buildingType= 'w' RETURN n"}, {...}, {...}
]}
The above its a Neo4J query, which I want to execute by sending a POST request like this:
mkr = requests.post(url, data=json.dumps(checkNode), headers=headers)
This is the procedure I follow:
First I convert the x into a string where x is:
x = {"statement":"MATCH (n:RealNode { id: "1" }) SET n.telecomType = 'P', n.buildingType= 'c' RETURN n"}
stringX = str(x)
Then I append this string into a list (mylist()). In the end the list has a number of strings inside.
Then I use the "join" method to join all the values inside the list and seperate them with comma:
allStatement = ','.join(mylist)
Then I create the variable "checkNode" which is the one I will send to my POST request:
checkNode = {'statements':[allStatement]}
Between the 4th and the 6th step I have tried a series of things such as replacing quotes and converting into string the variable "checkNode".
I sent the request:
mkr = requests.post(url, data=json.dumps(checkNode), headers=headers)
print(mkr.text)
The request never is sent. I printed the checkNode variable and it looks like this:
{'statements': ["{'statement': MATCH (n:RealNode { id: 'P3301041101' }) SET n.telecomType = 'P', n.buildingType= 'sealed' RETURN n},{'statement': CREATE (dsld:DslSldBconf {nodeType:'P3301041101', id: 'DSL-SLD48-BCONF-ALU', temaxia: '1'})}..."]}
I think one of the problems here is the double quotes after the [
I have spent hours experimenting with different parameters but I can not make it work. What am I doing wrong here? Thanks a lot!
You shouldn't be messing around with manual string processing; the json
module does all of that for you. What you want is more like:
x = {"statement":"MATCH (n:RealNode { id: "1" }) SET n.telecomType = 'P', n.buildingType= 'c' RETURN n"}
statement_list = [x]
# add any more statements to statement_list, probably using append()
checkNode = {'statements': statement_list}
mkr = requests.post(url, data=json.dumps(checkNode), headers=headers)
print(mkr.text)
Also, be careful of what's an str
and what's a bytes
, for what you send over the network.