@@ -21,6 +21,8 @@ static int json_decode_item(js_read_T *reader, typval_T *res);
2121
2222/*
2323 * Encode "val" into a JSON format string.
24+ * The result is in allocated memory.
25+ * The result is empty when encoding fails.
2426 */
2527 char_u *
2628json_encode (typval_T * val )
@@ -29,12 +31,16 @@ json_encode(typval_T *val)
2931
3032 /* Store bytes in the growarray. */
3133 ga_init2 (& ga , 1 , 4000 );
32- json_encode_item (& ga , val , get_copyID (), TRUE);
34+ if (json_encode_item (& ga , val , get_copyID (), TRUE) == FAIL )
35+ {
36+ vim_free (ga .ga_data );
37+ return vim_strsave ((char_u * )"" );
38+ }
3339 return ga .ga_data ;
3440}
3541
3642/*
37- * Encode ["nr", "val"] into a JSON format string.
43+ * Encode ["nr", "val"] into a JSON format string in allocated memory .
3844 * Returns NULL when out of memory.
3945 */
4046 char_u *
@@ -136,8 +142,11 @@ json_encode_item(garray_T *gap, typval_T *val, int copyID, int allow_none)
136142 case VVAL_FALSE : ga_concat (gap , (char_u * )"false" ); break ;
137143 case VVAL_TRUE : ga_concat (gap , (char_u * )"true" ); break ;
138144 case VVAL_NONE : if (!allow_none )
145+ {
139146 /* TODO: better error */
140147 EMSG (_ (e_invarg ));
148+ return FAIL ;
149+ }
141150 break ;
142151 case VVAL_NULL : ga_concat (gap , (char_u * )"null" ); break ;
143152 }
@@ -155,6 +164,7 @@ json_encode_item(garray_T *gap, typval_T *val, int copyID, int allow_none)
155164 break ;
156165
157166 case VAR_FUNC :
167+ case VAR_JOB :
158168 /* no JSON equivalent TODO: better error */
159169 EMSG (_ (e_invarg ));
160170 return FAIL ;
@@ -226,14 +236,15 @@ json_encode_item(garray_T *gap, typval_T *val, int copyID, int allow_none)
226236 }
227237 break ;
228238
229- #ifdef FEAT_FLOAT
230239 case VAR_FLOAT :
240+ #ifdef FEAT_FLOAT
231241 vim_snprintf ((char * )numbuf , NUMBUFLEN , "%g" , val -> vval .v_float );
232242 ga_concat (gap , numbuf );
233243 break ;
234244#endif
235- default : EMSG2 (_ (e_intern2 ), "json_encode_item()" ); break ;
236- return FAIL ;
245+ case VAR_UNKNOWN :
246+ EMSG2 (_ (e_intern2 ), "json_encode_item()" ); break ;
247+ return FAIL ;
237248 }
238249 return OK ;
239250}
0 commit comments