@@ -18,6 +18,10 @@ Interaction with JSON.
18
18
19
19
`
20
20
21
+ var (
22
+ JSON_DICT_TYPE = py .NewType ("JsonDict" , "JSON Key-Value Object" )
23
+ )
24
+
21
25
// serialize StringDict into JSON string
22
26
func json_dumps (self py.Object , args py.Tuple ) (py.Object , error ) {
23
27
if len (args ) == 0 {
@@ -35,10 +39,40 @@ func json_dumps(self py.Object, args py.Tuple) (py.Object, error) {
35
39
}
36
40
}
37
41
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
+
38
71
// Initialise the module
39
72
func init () {
40
73
methods := []* py.Method {
41
74
py .MustNewMethod ("dumps" , json_dumps , 0 , dumps_doc ),
75
+ py .MustNewMethod ("loads" , json_loads , 0 , "" ),
42
76
}
43
77
44
78
py .RegisterModule (& py.ModuleImpl {
0 commit comments