I am trying to import a file to Stata but can't get it work. I have the and the file is:
snd0007-1-1.0-json-ld.json
Help on how to do this would be appreciated
snd0007-1-1.0-json-ld.json
Help on how to do this would be appreciated
. which jsonio c:\ado\plus\j\jsonio.ado *! jsonio *! 22FEB2018 *! v 0.0.8
# json_to_kv_csv.py
import csv
import json
from pathlib import Path
src = Path("p:/snd0007-1-1.0-json-ld.json")
dst = src.with_name(src.stem + "_kv.csv")
with src.open(encoding="utf-8-sig") as f:
obj = json.load(f)
def flatten(x, path=""):
if isinstance(x, dict) and x:
for k, v in x.items():
k = str(k).replace("~", "~0").replace("/", "~1")
yield from flatten(v, path + "/" + k)
elif isinstance(x, list) and x:
for i, v in enumerate(x):
yield from flatten(v, path + "/" + str(i))
else:
yield path, json.dumps(x, ensure_ascii=False)
with dst.open("w", newline="", encoding="utf-8-sig") as f:
writer = csv.writer(f)
writer.writerow(["key", "value"])
writer.writerows(flatten(obj))
print(dst)
Comment