Skip to content

Commit 0ec6113

Browse files
committed
added JSON dumps
1 parent f712a5d commit 0ec6113

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

json/json.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package json
2+
3+
import (
4+
"encoding/json"
5+
"reflect"
6+
7+
"github.com/go-python/gpython/py"
8+
)
9+
10+
const dumps_doc = `dumps() -> str
11+
12+
Serialize obj to a JSON formatted str
13+
`
14+
15+
const module_doc = `
16+
17+
Interaction with JSON.
18+
19+
`
20+
21+
// serialize StringDict into JSON string
22+
func json_dumps(self py.Object, args py.Tuple) (py.Object, error) {
23+
if len(args) == 0 {
24+
return nil, py.ExceptionNewf(py.IndexError, "Too few arguments")
25+
} else {
26+
if reflect.TypeOf(args[0]).String() == "py.StringDict" {
27+
data, err := json.Marshal(args[0])
28+
if err != nil {
29+
return nil, py.ExceptionNewf(py.BaseException, "Failed to marshal JSON.")
30+
}
31+
return py.String(string(data)), nil
32+
} else {
33+
return nil, py.ExceptionNewf(py.TypeError, "Wrong type for json.dumps")
34+
}
35+
}
36+
}
37+
38+
// Initialise the module
39+
func init() {
40+
methods := []*py.Method{
41+
py.MustNewMethod("dumps", json_dumps, 0, dumps_doc),
42+
}
43+
44+
py.RegisterModule(&py.ModuleImpl{
45+
Info: py.ModuleInfo{
46+
Name: "json",
47+
Doc: module_doc,
48+
},
49+
Methods: methods,
50+
Globals: py.StringDict{},
51+
})
52+
53+
}

main

5.92 MB
Binary file not shown.

modules/runtime.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
"github.com/go-python/gpython/vm"
1919

2020
_ "github.com/go-python/gpython/builtin"
21+
_ "github.com/go-python/gpython/json"
2122
_ "github.com/go-python/gpython/math"
2223
_ "github.com/go-python/gpython/sys"
2324
_ "github.com/go-python/gpython/time"

0 commit comments

Comments
 (0)