Skip to content

Commit c19d480

Browse files
committed
Add a json method for objects.
1 parent 8b4622f commit c19d480

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

module.c

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,20 @@ static PyObject *object_call(ObjectData *self, PyObject *args, PyObject *kwds) {
6262
return quickjs_to_python(self->context, value);
6363
}
6464

65+
static PyObject *object_json(ObjectData *self) {
66+
JSValue global = JS_GetGlobalObject(self->context);
67+
JSValue JSON = JS_GetPropertyStr(self->context, global, "JSON");
68+
JSValue stringify = JS_GetPropertyStr(self->context, JSON, "stringify");
69+
JSValueConst args[1] = {self->object};
70+
JSValue json_string = JS_Call(self->context, stringify, JSON, 1, args);
71+
JS_FreeValue(self->context, global);
72+
JS_FreeValue(self->context, JSON);
73+
JS_FreeValue(self->context, stringify);
74+
return quickjs_to_python(self->context, json_string);
75+
}
76+
6577
static PyMethodDef object_methods[] = {
66-
{NULL} /* Sentinel */
78+
{"json", object_json, METH_NOARGS, "Converts to a JSON string."}, {NULL} /* Sentinel */
6779
};
6880

6981
static PyTypeObject Object = {PyVarObject_HEAD_INIT(NULL, 0).tp_name = "_quickjs.Object",

test_quickjs.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import json
12
import unittest
23

34
import quickjs
@@ -46,6 +47,15 @@ def test_function(self):
4647
""")
4748
self.assertEqual(self.context.eval("special(2)"), 42)
4849

50+
def test_error(self):
51+
with self.assertRaisesRegex(quickjs.JSException, "ReferenceError: missing is not defined"):
52+
self.context.eval("missing + missing")
53+
54+
55+
class Object(unittest.TestCase):
56+
def setUp(self):
57+
self.context = quickjs.Context()
58+
4959
def test_function_is_object(self):
5060
f = self.context.eval("""
5161
a = function(x) {
@@ -95,6 +105,6 @@ def test_function_call_unsupported_arg(self):
95105
with self.assertRaisesRegex(ValueError, "Unsupported type"):
96106
self.assertEqual(f({}), 42)
97107

98-
def test_error(self):
99-
with self.assertRaisesRegex(quickjs.JSException, "ReferenceError: missing is not defined"):
100-
self.context.eval("missing + missing")
108+
def test_json(self):
109+
d = self.context.eval("d = {data: 42};")
110+
self.assertEqual(json.loads(d.json()), {"data": 42})

0 commit comments

Comments
 (0)