Home > Mobile >  Add/keep black slashes to json dumps for API request
Add/keep black slashes to json dumps for API request

Time:03-10

I am working with an API that is weird. It accepts json but the object inside seems to be a stringed version of a listed object with slashes. In order to post the correct information to there server I would have to mimick this setup.

Take for example this request 's POST Object:

{"data":"[{\"type\":\"Hosting.Library.SpamStopper.Public.Operations.Module.GetEmailManagementLinksOperation\",\"operation\":{\"State\":0}}]","charge":true}

notice how it LOOKS like an Object>list>Object but inreality its a Object>stringified version of List>Object

I want to know how I can Programmably write out the same type of request dynamically.

So, for example, how can I change the State to 1?

I could say something like:

test = {"data":"[{\"type\":\"Hosting.Library.SpamStopper.Public.Operations.Module.GetEmailManagementLinksOperation\",\"operation\":{\"State\":0}}]","charge":True}
testchange = json.loads(test["data"])
testchange[0]["operation"]["State"] = 1
print(testchange)

but then how do I convert it back so I can send off the request?

CodePudding user response:

I'm not sure you will be able to perform what you are trying to do, since the python interpreter is going to absorb those single black-slashes \.

I had similar problems with APIs very specific with their JSONs. I was able to fix the problems being sure that my headers explicitly state my "Content-Type: application/json" and/or using something like this:

testjson = json.dumps(testdata).encode("utf-8")

I hope this helps you somehow. Also, if you could provide some API examples where we could do some testing, or any information about the technology this backend is running, we could try to help you more.

CodePudding user response:

I figured out the answer:

test = {"data":"[{\"type\":\"Hosting.Library.SpamStopper.Public.Operations.Module.GetEmailManagementLinksOperation\",\"operation\":{\"State\":0}}]","charge":True}
testchange = json.loads(test["data"])
testchange[0]["operation"]["State"] = 1
test["data"] = json.dumps(testchange).replace('"',r'\"')
print(test)

The idea is to put the slashes back once I am done with the object and use json.dumps to stringify the object. Very weird api but maybe useful if I run across something like this again.

  • Related