Escape characters not working when extracted from JSON

Viewed 199

I am trying to build a very simple code SQL code formatter, which extracts the query from a JSON object and the goal is to copy the final output to the clipboard. I have not got to the clipboard part yet, because I could not get Python to interpret escape characters.

print function prints the whole thing with escape characters and all, and I cannot figure out why.

import json

main_query = {"text": "SELECT\n  * from test          where id = 1\n    LIMIT 10"}

query = str(json.dumps(main_query['text']).strip('"'))

print(query) # Not working
print('{}'.format(query)) # Not working either

"""
Output:

SELECT\n  * from test          where id = 1\n    LIMIT 10
SELECT\n  * from test          where id = 1\n    LIMIT 10
"""
4 Answers

It's also important to understand why this happens.

When you do json.dumps() on a string you get the representation of the string.

For example, if you do print(repr(main_query["text])), you'll get this output:

SELECT \n  * from test          where id = 1 \n    LIMIT 10

However, there's no need to do repr() or json.dumps over a string that has newlines and you want for these newlines to be printed as such.

If you only do:

import json

main_query = {"text": "SELECT \n  * from test          where id = 1 \n    LIMIT 10"}

query = main_query['text'].strip('"')

print(query)

You'll get the string as you want:

SELECT
  * from test          where id = 1
    LIMIT 10

Just try this:

main_query = {"text": "SELECT\n  * from test          where id = 1\n    LIMIT 10"}
print(main_query["text"])
SELECT
  * from test          where id = 1
    LIMIT 10
import json
import re
main_query = {"text": "SELECT\n  * from test          where id = 1\n    LIMIT 10"}
query = main_query['text']
print(re.sub('\n',' ',query))

Use this buddy, Lists and Loop Print implementation

import json
main_query = {"text": "SELECT\n  * from test          where id = 1\n    LIMIT 10"}
query = str(json.dumps(main_query['text']).strip('"'))
for word in query.split('\\n'):
  print(word)
Related