Skip to content

Instantly share code, notes, and snippets.

@Timothy-Liuxf
Last active April 21, 2022 09:07
Show Gist options
  • Save Timothy-Liuxf/ac602674ec6a469c4cda645cb803f3e4 to your computer and use it in GitHub Desktop.
Save Timothy-Liuxf/ac602674ec6a469c4cda645cb803f3e4 to your computer and use it in GitHub Desktop.
Extract codes in the form of raw string of json and write to source code file.
################################################################################
# Suppose we have a json file `jcodes.json` as shown which contains some C++
# code as string. This python program can generate C++ source files containing
# the code.
################################################################################
import json
import os
with open("jcodes.json", "r", encoding="utf-8") as code:
lists = json.load(code)["codes"]
for list in lists:
path = list["id"]
if not os.path.exists(path):
os.makedirs(path)
with open(path + "/code.cpp", "w", encoding="utf-8") as target:
target.write(list["code"])
{
"_comment": "A json example",
"codes": [
{
"id": "hello_world",
"code": "#include <iostream>\n\nint main()\n{\n\tstd::cout << \"Hello, world!\\n\" << std::endl;\n\treturn 0;\n}\n"
},
{
"id": "goodbye_world",
"code": "#include <iostream>\n\nint main()\n{\n\tstd::cout << \"Goodbye, world!\\n\" << std::endl;\n\treturn 0;\n}\n"
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment