0

the code

import json

jsonData = {
    'url' : 'test/file.jpg'
}

arrayData = json.dumps(jsonData)

# load the json to a string
resp = json.loads(arrayData)

resp['url'] = resp['url'].replace(r'/',r'\/')

print('without JSON output:',resp['url'])

jsonDataNew = [
    {'url' : str(resp['url'])}
]

json_data = json.dumps(jsonDataNew)
json_data = json.loads(json_data)
print('with JSON output')
print(json_data)

the output

without JSON output: test\/file.jpg
with JSON output
[{'url': 'test\\/file.jpg'}]

the desired output would be

with JSON output
[{'url': 'test\/file.jpg'}]

no matter how, im not able to remove the escape in the JSON output, even converted into JSON file. is this something unavoidable in Python?

9
  • you mean you want it like \ instead of \\? Commented Aug 16, 2022 at 20:49
  • this is the input "test/file.jpg" i want to it be "test\/file.jpg" in JSON output Commented Aug 16, 2022 at 20:50
  • hmm, if i print json_data[0]['url'] at the end, I do get test\/file.jpg as expected. Commented Aug 16, 2022 at 20:55
  • print as string it looks perfect. can you try to print as JSON format? the extra / appears. Commented Aug 16, 2022 at 20:58
  • hmm, good question. because json.loads('[{"url": "test\/file.jpg"}]') totally works too. Commented Aug 16, 2022 at 21:07

1 Answer 1

1

This is because it uses backslash to escape backslash. In that sense, the double backslash you saw is actually interpreted as a single character.

For an example,

>>> a = 'test\\'
>>> a
'test\\'
>>> print(a)
test\

You can read up for more on repr

On the other hand, if what you want to do is to escape the forward slashes. Perhaps the easier and cleaner solution is to use ujson.

import ujson
    
jsonData = {
   'url' : 'test/file.jpg'
} 
json_data = ujson.dumps(jsonData, escape_forward_slashes=True)
print(json_data)

The output will be :

{"url":"test\/file.jpg"}
Sign up to request clarification or add additional context in comments.

1 Comment

ujson with escape_forword_slashes does the job! what if in the value we need to have 2 different formats one with escape and one without? example: ` #with JSON output [ {'url': ['test\/file.jpg', 'test/file.jpg'] ] `

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.