Skip to content

Instantly share code, notes, and snippets.

@syohex
Created May 30, 2016 11:43
Show Gist options
  • Save syohex/df85dc0c5aaedff32b09abc97a729c53 to your computer and use it in GitHub Desktop.
Save syohex/df85dc0c5aaedff32b09abc97a729c53 to your computer and use it in GitHub Desktop.
Convert from JSON to Golang struct definition in Python
#!/usr/bin/env python
import sys
import os
import json
def usage():
print("Usage: json2gostruct.py struct_name")
os.exit(0)
def indent(nest):
return "\t" * nest
def guess_list_type(lst, name, nest):
if len(lst) == 0:
return "string"
first_type = type(lst[0])
if first_type == dict:
return encode(lst[0], name, nest)
elif first_type == list:
return "[]" . guess_array_type(lst[0], name, nest)
elif first_type == str:
return "string"
elif first_type == float:
return "float64"
elif first_type == int:
return "int"
else:
print("Unknown type: '{}'".format(first_type))
exit(1)
def encode_element(obj, name, nest):
ret = []
for (k, v) in obj.items():
v_type = type(v)
if v_type == dict:
elm_type = encode(v, name, nest)
elif v_type == list:
elm_type = "[]" + guess_list_type(v, name, nest)
elif v_type == int:
elm_type = "int"
elif v_type == float:
elm_type = "float64"
else:
elm_type = "string"
field_decl = "{}{} {} `json:{}`".format(indent(nest), k.capitalize(), elm_type, k)
ret.append(field_decl)
return ret
def encode(obj, name, nest):
lines = []
if nest == 0:
lines.append("type {} struct {{".format(name))
else:
lines.append("struct {")
for line in encode_element(obj, name, nest+1):
lines.append(line)
if nest == 0:
lines.append("}\n")
else:
lines.append(indent(nest) + "}")
return "\n".join(lines)
if __name__ == '__main__':
if len(sys.argv) == 1:
print("Missing struct name")
usage()
struct_name = sys.argv[1]
obj = json.loads(sys.stdin.read())
struct_def = encode(obj, struct_name, 0)
print(struct_def)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment