Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ArtOfCode-
Last active November 13, 2015 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ArtOfCode-/2609146ac6e92d05ccd2 to your computer and use it in GitHub Desktop.
Save ArtOfCode-/2609146ac6e92d05ccd2 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
JSON Post Processor - ArtOfCode
-------------------------------
The MIT License (MIT)
Copyright (c) 2015 ArtOfCode
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-------------------------------
Call this script by running:
jsonpostprocess <input> <output> <scope>
If your input data is in `file.json`, you want to output to `processed.json`, and you
want to remove the `posts` scope:
jsonpostprocess file.json processed.json posts
"""
import sys
import json
def main():
if len(sys.argv) < 4:
print("Not enough parameters!")
sys.exit(1)
else:
filename = sys.argv[1]
output = sys.argv[2]
scope = sys.argv[3]
print("Decoding input file '{0}' to output '{1}'. Removing scope '{2}'.".format(filename, output, scope))
with open(filename, "r") as input_file:
try:
json_data = json.loads(input_file.read())
except:
print("JSON decoding failed.")
sys.exit(3)
if scope in json_data:
json_scope = json_data[scope]
json_objects = json_scope["row"]
with open(output, "w") as output_file:
try:
for item in json_objects:
new_item = {}
for key, val in item.items():
if key[0] == "@":
new_item[key[1:]] = val
else:
new_item[key] = val
output_file.write("{0}\n".format(json.dumps(new_item, True, True)))
except:
print("Serialization failed.")
sys.exit(4)
print("Converted.")
sys.exit(0)
else:
print("Scope does not exist in input JSON.")
sys.exit(2)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment