Skip to content

Instantly share code, notes, and snippets.

@giavac
Created July 12, 2023 15:37
Show Gist options
  • Save giavac/2f56e28eb1bc6997158dd5420fd9f2ee to your computer and use it in GitHub Desktop.
Save giavac/2f56e28eb1bc6997158dd5420fd9f2ee to your computer and use it in GitHub Desktop.
Convert a multiline string into a CString usable with C code
#!/usr/local/bin/python3
import json
import argparse
def rewrite_as_c_string(json_str):
data = json.loads(json_str)
formatted_json = json.dumps(data, indent=4)
c_string = '"' + formatted_json.replace('"', '\\"').replace('\n', '\\n"\n"') + '"'
return c_string
def main(args):
es = args.input
#us = es.replace('\\\\\"', '"')
#us = es.replace('\\"', '"').replace('\\t', '').replace('\\n', '')
us = es.replace('\\\\\"', '"').replace('\\"', '"').replace('\\t', '').replace('\\n', '').replace('\\', '')
#us = urllib.parse.unquote(es)
# print()
# print(us)
json_object = json.loads(us)
formatted_json = json.dumps(json_object, indent=4)
# print(formatted_json)
c_string = rewrite_as_c_string(formatted_json)
print(c_string)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="A script to transform a multiline string into a CString")
parser.add_argument("-i", "--input", required=True, help="Input string")
args = parser.parse_args()
main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment