Jun 03, 2014 This approach works only if the nulls to delete are on the end of the line (In my case i have lines long 1000+ with 600 characters of null on the end). Just copy the whole thing, and past it on a new file tab, and automatically notepad will replace all nulls in spaces.
I have a JSON file with this data
How can I delete any key-value pairs that contain null, false and true of this file, using Python?
These values can appear in various level of the data structure.
Cœur1 Answer
By decoding, processing the object recursively, and encoding to JSON again.
I like to use single dispatch for such tasks:
I used is not False
, etc. to test for the exact objects. Had I used v not in {None, False, True}
the integer values 0
and 1
would be removed too as False
and True
are equal to those values, respectively.
Demo against your sample loaded into data
:
Not the answer you're looking for? Browse other questions tagged pythonjsonpython-3.x or ask your own question.
I have a shell script and I want to add a line or two where it would remove a log file only if it exists. Currently my script simply does:
However if the filename doesn't exist I get a message saying filename.log does not exist, cannot remove. This makes sense but I don't want to keep seeing that every time I run the script. Is there a smarter way with an IF statement I can get this done?
codeforester4 Answers
Pass the -f
argument to rm
, which will cause it to treat the situation where the named file does not exist as success, and will suppress any error message in that case:
What you literally asked for would be more like:
but it's more to type and adds extra failure modes. (If something else deleted the file after [
tests for it but before rm
deletes it, then you're back at having a failure again).
As an aside, the --
s cause the filename to be treated as literal even if it starts with a leading dash; you should use these habitually if your names are coming from variables or otherwise not strictly controlled.
Touch the file first, which will create it if it's not present, but only change the timestamp if it is present.
Less efficient, but easy to remember.
mahemoff