![]() |
Parsing JSON with backslashes - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Parsing JSON with backslashes (/thread-23958.html) |
Parsing JSON with backslashes - bazcurtis - Jan-24-2020 I have a script where the users will need to edit some variables. I don't want them to mess the script up so decided I would make a config json file where they could just edit the json rather than edit the script. I don't want the users to have to understand \\, I want them to fill it in the way you would normally type a file path or domain user account. The problem is I get a json.decoder.JSONDecodeError: Invalid \uXXXX escape: line 5 column 22 (char 243) error. I understand why this is, but is there a way I can make it easy for the user, and Python ignore the error. Once I have parsed the JSON I will sort out the paths so Python can understand them. def read_json_config(): with open('console_config.json') as json_data: json_config_file = json.load(json_data)This is my JSON file. { "ClientID":"8477295f-405", "ClientSecret":"10f35a425670847eb63d9b1954592d2b8305cd87e3", "ReportName":"Unprotected_Machines_", "ReportFilePath":"c:\users\accounts\desktop\reports\", "ConsoleName":"UK PS", "SearchDomain":"dc=domain,dc=co,dc=uk", "SearchUser":"domain\dap.l", "SearchUserPassword":"password", "DomainController":"10.0.1.20" } RE: Parsing JSON with backslashes - micseydel - Jan-24-2020 You might be able to achieve that with a custom parser but I really, really wouldn't recommend that. If a regular Python file doesn't work for you, I'd recommend you give this a look. RE: Parsing JSON with backslashes - snippsat - Jan-24-2020 Two errors in this path because of escape characters. >>> s = "c:\users\accounts\desktop\reports" # Removed last \ File "<interactive input>", line 1 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \uXXXX escape >>> # Fix >>> s = "c:\\users\\accounts\\desktop\\reports\\" >>> s 'c:\\users\\accounts\\desktop\\reports\\' >>>Do no use single \ in file paths.import json from pprint import pprint def read_json_config(): with open('c.json') as json_data: json_config_file = json.load(json_data) pprint(json_config_file) read_json_config()
RE: Parsing JSON with backslashes - bazcurtis - Feb-08-2020 (Jan-24-2020, 06:21 PM)micseydel Wrote: You might be able to achieve that with a custom parser but I really, really wouldn't recommend that. If a regular Python file doesn't work for you, I'd recommend you give this a look. This worked a treat. I have converted all my scripts that needed this option. They work perfectly. Thank you very much. |