I am getting this as my response
b'{"userdetails":[["{\\”user_id\\":[\\”54562af66ffd\\"],\\”user_name\\":[\\"bewwrking\\"],\\”room\\":[\\"31\\”]}'
I want to convert it into proper json without any double slashes.
Is there any buildin function for that or i need to do string replace
If you have control over how it is being sent, I would recommend doing to_string on any relevant field/keys that you are sending as json. I had some weird json responses before sanitizing the input to json_dump.
remove the leading b and run replace as below.
s = '{"userdetails":[["{\\"user_id\\":[\\"54562af66ffd\\"],\\"user_name\\":[\\"bewwrking\\"],\\"room\\":[\\"31\\"]}'
s = s.replace('\','')
print(s)
{"userdetails":[["{"user_id":["54562af66ffd"],"user_name":["bewwrking"],"room":["31"]}
Related
I am writing a program to call an API. I am trying to convert my data payload into json. Thus, I am using json.loads() to achieve this.
However, I have encountered the following problem.
I set my variable as following:
apiVar = [
"https://some.url.net/api/call", #url
'{"payload1":"email#user.net", "payload2":"stringPayload"}',#payload
{"Content-type": "application/json", "Accept": "text/plain"}#headers
]
Then I tried to convert apiVar[1] value into json object.
jsonObj = json.loads(apiVar[1])
However, instead of giving me output like the following:
{"payload1":"email#user.net", "payload2":"stringPayload"}
It gives me this instead:
{'payload1':'email#user.net', 'payload2':'stringPayload'}
I know for sure that this is not a valid json format. What I would like to know is, why does this happen? I try searching a solution for it but am not able to find anything on it. All code examples suggest it should have given me the double quote instead.
How should I fix it so that it will give the double quote output?
json.loads() takes a JSON string and converts it into the equivalent Python datastructure, which in this case is a dict containing strings. And Python strings display in single quotes by default.
If you want to convert a Python datastructure to JSON, use json.dumps(), which will return a string. Or if you're outputting straight to a file, use json.dump().
In any case, your payload is already valid JSON, so the only reason to load it is if you want to make changes to it before calling the API.
You need to use the json.dumps to convert the object back into json format.
The string with single quotes that you are reverencing is probably a str() or repr() method that is simply used to visualize the data as a python object (dictionary) not a json object. try taking a look at this:
print(type(jsonObj))
print(str(jsonObj))
print(json.dumps(jsonObj))
I've got a JSON file that was converted to a string in Python. Somehow along the way the double quotes have gotten replaced with single quotes.
{\'MyJSON\': {\'Report\': \'1\' ....
I need to convert my string so that it is in this format instead:
{\"MyJSON\": {\"Report\": \"1\" ....
My problem is that using str.replace, I can't figure out how to convert a single quote into a double quote as both quotes are escaped.
My ultimate goal is to be able to put the string into json.loads so that I can pretty print it.
Attempts:
txt.replace(r"\'", r'\"')
> "{'MyJSON': {'Report': '1'"
txt.replace("\"", "\'")
> "{'MyJSON': {'Report': '1'"
If I save my string to a txt file it appears in the preview as:
{'MyJSON': {'Report': '1' ...
So I think what I actually need to do is replace ' with "
I have decided to use ast.literal_eval(txt) which can convert my string to a dictionary. From there, json.loads(json.dumps(dict)) gets me to JSON
i mean,
my_string = "\"\'"
print(my_string.replace("\'", "\""))
works perfectly fine
EDIT: i didn't mean use this directly, it was a proof of concept. In mine the replacement was reversed. I have updated this snippet such that it could directly be put into your code. Try it again
Instead of focusing on the backslashes to try to "hack" a json string / dict str into a JSON, a better solution is to take it one step at a time and start by converting my dict string into a dictionary.
import ast
txt = ast.literal_eval(txt) # convert my string to a dictionary
txt = json.loads(json.dumps(txt)) # convert my dict to JSON
I need to make a request to the api of my client, and the api returns this data:
[6,0,'VT3zrYA',5,'USUeZWA',5,0,0,0,0,0,4,0,0,0,2,0,0,3,0,0,0,0,2,0,1,["portale.titolari.client.config.ShoulderDTO/4121330600","java.util.HashSet/3273092938","MATTEO SBRAGIA","java.util.ArrayList/4159755760","java.util.Date/3385151746","MATTEO"],0,7]
How can I parse this data and extract the following fields :
MATTEO SBRAGIA
MATTEO
I've tried this code, but it's not working :
data = json.load(output_data)
pprint data
This in fact is not a valid JSON string because it contains single quotes '. You can replace all single quotes with double quotes and then parse the string but it's a question whether this was intentional or a mistake:
import json
s = '[6,0,\'VT3zrYA\',5,\'USUeZWA\',5,0,0,0,0,0,4,0,0,0,2,0,0,3,0,0,0,0,2,0,1,["portale.titolari.client.config.ShoulderDTO/4121330600","java.util.HashSet/3273092938","MATTEO SBRAGIA","java.util.ArrayList/4159755760","java.util.Date/3385151746","MATTEO"],0,7]'
data = json.loads(s.replace("\'", '"'))
print(data[26][2])
print(data[26][5])
prints:
$ python test.py
MATTEO SBRAGIA
MATTEO
so i do this get request to a Steam page where it responds this JSON:
{"success":true,"lowest_price":"$2.23","volume":"2,842","median_price":"$2.24"}
My objective is to transform it into a dictionary in Python, but what i get when i return the JSON object in my function is this:
{u'volume': u'2,842', u'median_price': u'2,02€ ',
u'lowest_price': u'1,99€ ', u'success': True} (notice the u').
What can i do to eliminate the u's?
You're seeing Python letting you know that the strings you're printing are unicode strings. Unless the output you're seeing really matters (e.g., it's input for something else), you can generally disregard the leading 'u' character until you run into issues with unicode output.
There are a litany of stack overflow questions which address this.
Python string prints as [u'String']
What's the u prefix in a python string
Printing a string prints 'u' before the string in Python?
And a lot more....
You could import json module and use json.dumps to prettify your output.
import json
response = {"success":True,"lowest_price":"$2.23","volume":"2,842","median_price":"$2.24"}
print json.dumps(response, indent=2)
I have got a url in this form - http:\\/\\/en.wikipedia.org\\/wiki\\/The_Truman_Show. How can I make it normal url. I have tried using urllib.unquote without much success.
I can always use regular expressions or some simple string replace stuff. But I believe that there is a better way to handle this...
urllib.unquote is for replacing %xx escape codes in URLs with the characters they represent. It won't be useful for this.
Your "simple string replace stuff" is probably the best solution.
Have you tried using json.loads from the json module?
>>> json.loads('"http:\\/\\/en.wikipedia.org\\/wiki\\/The_Truman_Show"')
'http://en.wikipedia.org/wiki/The_Truman_Show'
The input that I'm showing isn't exactly what you have. I've wrapped it in double quotes to make it valid json.
When you first get it from the json, how are you decoding it? That's probably where the problem is.
It is too childish -- look for some library function when you can transform URL by yourself.
Since there are not other visible rules but "/" replaced by "\/", you can simply replace it back:
def unescape_this(url):
return url.replace(r"\\/", "/")