In BASH, I can store JSON into an environment variable via jq:
export FOO=$(curl ... | jq -Rs)
Now, if I load that into python:
bar=os.environ["FOO"]
bar
will have something like: {\"this\":\"that\"}
, which is a problem when loading with json
:
json.loads(bar) # error
I have tried a few things including repr
, rf'{os.environ["FOO"]}'
and so on, but there doesn’t seem to be an internally managed way to drop the extra slashes.
How do I drop the extra slashes via string functions? I’d prefer not to simply replace them with a single slash, as I might have to touch that code again sometime in the future.
2
Answers
I tried to reconstruct this:
This is what is stored from the looks in bash:
Then in python shell:
So basically json.loads() doesn’t give you any guarantees regarding the type of Python object you get, but it tries to de-serialize whatever you feed it and so a nested de-serialization does the job. But of course, it is better, if you can make sure that the environment contains the data in the correct format in the first place as the other answer suggests.
Add the
-r
flag to output as raw text fromjq
. Here is an example using echo that gives the escaped results:But adding
-r
gives a result that is still in JSON format without all of the escaped quotes:Which is parseable by Python.