Reputation: 75
I have looked around and have only found answers to writing out a directory tree to a JSON file - which is fine but doesn't solve my current issue. I'm looking for either the syntax to do this OR a better method for my overall problem.
High level: I'm working on a Python wrapper of some enterprise software to automate some testing. Ideally I can ship off a config file with the code so that whoever runs the tests just needs to worry about the config file and not the code itself. I'd like to include directory paths in the config file since those are relative to the machine the code is being run on. I would love for there to be an equivalent to a string literal for JSON that exists in Python
r"This\Type\Of\Thing!"
so that I can simply have something like this:
{"relevant_paths": {
"path1": r"C:\users\whatever\path",
"path2": r"C:\useres\another\whatever\path\"
}
}
to access them as dict values, but as you already know, it doesn't. Also the single-quote isn't working for me as an escape character, unless it's just PyCharm complaining and I don't understand why (very possible).
So is there a way to include directory paths in the JSON or should I actually rethink how I'm shipping this off?
Upvotes: 0
Views: 5660
Reputation: 2217
Just include the raw string. JSON has never given me issues with storing a path as above, however it DOES escape the backslashes in paths, as it should and as the JSON spec requires.
Python 3.4.9 (default, Aug 14 2018, 21:28:57)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> _tmp = {}
>>> _tmp['relevant_paths'] = {}
>>> _tmp['relevant_paths']['path1'] = r'C:\users\whatever\path',
>>> _tmp['relevant_paths']['path2'] = r'C:\useres\another\whatever\path'
>>> import json
>>> print(json.dumps(_tmp, indent=4))
{
"relevant_paths": {
"path2": "C:\\useres\\another\\whatever\\path",
"path1": "C:\\users\\whatever\\path"
}
}
The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks. All Unicode characters may be placed within the quotation marks, except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).
(Note: A reverse solidus is a backslash and is required to be escaped in properly formatted JSON.)
Upvotes: 2