Skip to content

Commit 6fa2005

Browse files
committed
some more basic changes
1 parent 0748975 commit 6fa2005

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

json/json.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ Interaction with JSON.
1818
1919
`
2020

21+
var (
22+
JSON_DICT_TYPE = py.NewType("JsonDict", "JSON Key-Value Object")
23+
)
24+
2125
// serialize StringDict into JSON string
2226
func json_dumps(self py.Object, args py.Tuple) (py.Object, error) {
2327
if len(args) == 0 {
@@ -35,10 +39,40 @@ func json_dumps(self py.Object, args py.Tuple) (py.Object, error) {
3539
}
3640
}
3741

42+
// de-serialize JSON formatted string into JsonDict
43+
func json_loads(self py.Object, args py.Tuple) (py.Object, error) {
44+
if len(args) == 0 {
45+
return nil, py.ExceptionNewf(py.TypeError, "Too few arguments")
46+
} else {
47+
if reflect.TypeOf(args[0]).String() == "py.String" {
48+
var result map[string]interface{}
49+
arg, err := py.ReprAsString(args[0])
50+
if err != nil {
51+
return nil, py.ExceptionNewf(py.TypeError, "Failed to parse argument into Go string.")
52+
}
53+
err = json.Unmarshal([]byte(arg), result)
54+
if err != nil {
55+
return nil, py.ExceptionNewf(py.KeyError, "Failed to parse JSON")
56+
}
57+
parsedDict := JSON_DICT_TYPE.Alloc()
58+
for k, v := range result {
59+
switch c := v.(type) {
60+
case string:
61+
parsedDict.Dict[k] = py.String(c)
62+
}
63+
}
64+
return parsedDict, nil
65+
} else {
66+
return nil, py.ExceptionNewf(py.KeyError, "Argument must be of type string")
67+
}
68+
}
69+
}
70+
3871
// Initialise the module
3972
func init() {
4073
methods := []*py.Method{
4174
py.MustNewMethod("dumps", json_dumps, 0, dumps_doc),
75+
py.MustNewMethod("loads", json_loads, 0, ""),
4276
}
4377

4478
py.RegisterModule(&py.ModuleImpl{

main

81.9 KB
Binary file not shown.

0 commit comments

Comments
 (0)