2121static int json_encode_item (garray_T * gap , typval_T * val , int copyID , int options );
2222static int json_decode_item (js_read_T * reader , typval_T * res , int options );
2323
24+ /*
25+ * Encode "val" into a JSON format string.
26+ * The result is added to "gap"
27+ * Returns FAIL on failure and makes gap->ga_data empty.
28+ */
29+ static int
30+ json_encode_gap (garray_T * gap , typval_T * val , int options )
31+ {
32+ if (json_encode_item (gap , val , get_copyID (), options ) == FAIL )
33+ {
34+ ga_clear (gap );
35+ gap -> ga_data = vim_strsave ((char_u * )"" );
36+ return FAIL ;
37+ }
38+ return OK ;
39+ }
40+
2441/*
2542 * Encode "val" into a JSON format string.
2643 * The result is in allocated memory.
2744 * The result is empty when encoding fails.
28- * "options" can be JSON_JS or zero;
45+ * "options" can contain JSON_JS, JSON_NO_NONE and JSON_NL.
2946 */
3047 char_u *
3148json_encode (typval_T * val , int options )
@@ -34,25 +51,21 @@ json_encode(typval_T *val, int options)
3451
3552 /* Store bytes in the growarray. */
3653 ga_init2 (& ga , 1 , 4000 );
37- if (json_encode_item (& ga , val , get_copyID (), options ) == FAIL )
38- {
39- vim_free (ga .ga_data );
40- return vim_strsave ((char_u * )"" );
41- }
54+ json_encode_gap (& ga , val , options );
4255 return ga .ga_data ;
4356}
4457
4558/*
4659 * Encode ["nr", "val"] into a JSON format string in allocated memory.
47- * "options" can be JSON_JS or zero;
60+ * "options" can contain JSON_JS, JSON_NO_NONE and JSON_NL.
4861 * Returns NULL when out of memory.
4962 */
5063 char_u *
5164json_encode_nr_expr (int nr , typval_T * val , int options )
5265{
5366 typval_T listtv ;
5467 typval_T nrtv ;
55- char_u * text ;
68+ garray_T ga ;
5669
5770 nrtv .v_type = VAR_NUMBER ;
5871 nrtv .vval .v_number = nr ;
@@ -65,9 +78,11 @@ json_encode_nr_expr(int nr, typval_T *val, int options)
6578 return NULL ;
6679 }
6780
68- text = json_encode (& listtv , options );
81+ ga_init2 (& ga , 1 , 4000 );
82+ if (json_encode_gap (& ga , & listtv , options ) == OK && (options & JSON_NL ))
83+ ga_append (& ga , '\n' );
6984 list_unref (listtv .vval .v_list );
70- return text ;
85+ return ga . ga_data ;
7186}
7287
7388 static void
0 commit comments