@@ -26,7 +26,6 @@ function pythonBridge(opts) {
2626 function wrapper ( ) {
2727 self = self || wrapper ;
2828 let code = json . apply ( this , arguments ) ;
29- let on_message , on_close ;
3029
3130 if ( ! ( this && this . connected || self . connected ) ) {
3231 return Promise . reject ( new PythonBridgeNotConnected ( ) ) ;
@@ -40,7 +39,7 @@ function pythonBridge(opts) {
4039 function onMessage ( data ) {
4140 ps . removeListener ( 'close' , onClose ) ;
4241 if ( data && data . type && data . type === 'success' ) {
43- resolve ( data . value ) ;
42+ resolve ( eval ( `( ${ data . value } )` ) ) ;
4443 } else if ( data && data . type && data . type === 'exception' ) {
4544 reject ( new PythonException ( data . value ) ) ;
4645 } else {
@@ -176,13 +175,45 @@ function dedent(code) {
176175
177176function json ( text_nodes ) {
178177 let values = Array . prototype . slice . call ( arguments , 1 ) ;
179- return dedent ( text_nodes . reduce ( ( cur , acc , i ) => cur + JSON . stringify ( values [ i - 1 ] ) + acc ) ) ;
178+ return dedent ( text_nodes . reduce ( ( cur , acc , i ) => {
179+ return cur + serializePython ( values [ i - 1 ] ) + acc ;
180+ } ) ) ;
181+ }
182+
183+ function serializePython ( value ) {
184+ if ( value === null || typeof value === 'undefined' ) {
185+ return 'None' ;
186+ } else if ( value === true ) {
187+ return 'True' ;
188+ } else if ( value === false ) {
189+ return 'False' ;
190+ } else if ( value === Infinity ) {
191+ return "float('inf')" ;
192+ } else if ( value === - Infinity ) {
193+ return "float('-inf')" ;
194+ } else if ( value instanceof Array ) {
195+ return `[${ value . map ( serializePython ) . join ( ', ' ) } ]` ;
196+ } else if ( typeof value === 'number' ) {
197+ if ( isNaN ( value ) ) {
198+ return "float('nan')" ;
199+ }
200+ return JSON . stringify ( value ) ;
201+ } else if ( typeof value === 'string' ) {
202+ return JSON . stringify ( value ) ;
203+ } else if ( value instanceof Map ) {
204+ const props = Array . from ( value . entries ( ) ) . map ( kv => `${ serializePython ( kv [ 0 ] ) } : ${ serializePython ( kv [ 1 ] ) } ` ) ;
205+ return `{${ props . join ( ', ' ) } }` ;
206+ } else {
207+ const props = Object . keys ( value ) . map ( k => `${ serializePython ( k ) } : ${ serializePython ( value [ k ] ) } ` ) ;
208+ return `{${ props . join ( ', ' ) } }` ;
209+ }
180210}
181211
182212pythonBridge . pythonBridge = pythonBridge ;
183213pythonBridge . PythonException = PythonException ;
184214pythonBridge . PythonBridgeNotConnected = PythonBridgeNotConnected ;
185215pythonBridge . isPythonException = isPythonException ;
186216pythonBridge . json = json ;
217+ pythonBridge . serializePython = serializePython ;
187218
188219module . exports = pythonBridge . pythonBridge = pythonBridge ;
0 commit comments