44 isObjectExpression ,
55 isNullLiteral ,
66 isNumericLiteral ,
7+ isUnaryExpression ,
78 isStringLiteral ,
89 ObjectExpression ,
910 ObjectProperty ,
@@ -60,30 +61,43 @@ const isConvertibleObjectProperty = (properties: ObjectProperty[]) => {
6061 return properties . every ( node => ! node . computed )
6162}
6263
63- export function converter ( node : object | null | undefined ) : unknown {
64- if ( ! isValidJsonValue ( node ) ) {
65- throw new Error ( 'Invalid value is included. ')
64+ const createSafeStringForJsonParse = ( value : string ) => {
65+ if ( / \\ / . test ( value ) ) {
66+ value = value . replace ( / \\ / g , '\\\\ ')
6667 }
6768
68- if ( isStringLiteral ( node ) ) {
69- let { value } = node
70- if ( / \\ / . test ( value ) ) {
71- value = value . replace ( / \\ / g, '\\\\' )
72- }
69+ if ( / " / . test ( value ) ) {
70+ value = value . replace ( / " / g, '\\"' )
71+ }
7372
74- if ( / " / . test ( value ) ) {
75- value = value . replace ( / " / g, '\\"' )
73+ if ( / [ \t \f \r \n \b ] / g. test ( value ) ) {
74+ const codes = [ '\f' , '\r' , '\n' , '\t' , '\b' ]
75+ const replaceCodes = [ '\\f' , '\\r' , '\\n' , '\\t' , '\\b' ]
76+ for ( let i = 0 ; i < codes . length ; i ++ ) {
77+ value = value . replace ( new RegExp ( codes [ i ] ) , replaceCodes [ i ] )
7678 }
79+ }
7780
78- if ( / [ \t \f \r \n \b ] / g. test ( value ) ) {
79- const codes = [ '\f' , '\r' , '\n' , '\t' , '\b' ]
80- const replaceCodes = [ '\\f' , '\\r' , '\\n' , '\\t' , '\\b' ]
81- for ( let i = 0 ; i < codes . length ; i ++ ) {
82- value = value . replace ( new RegExp ( codes [ i ] ) , replaceCodes [ i ] )
83- }
81+ return value
82+ }
83+
84+ export function converter ( node : object | null | undefined ) : unknown {
85+ // for negative number, ex) -10
86+ if ( isUnaryExpression ( node ) ) {
87+ const { operator, argument } = node
88+ if ( operator === '-' && isNumericLiteral ( argument ) ) {
89+ return - argument . value
8490 }
91+ }
8592
86- return value
93+ if ( ! isValidJsonValue ( node ) ) {
94+ throw new Error ( 'Invalid value is included.' )
95+ }
96+
97+ if ( isStringLiteral ( node ) ) {
98+ const { value } = node
99+ const safeValue = createSafeStringForJsonParse ( value )
100+ return safeValue
87101 }
88102
89103 if ( isNullLiteral ( node ) ) {
@@ -106,7 +120,10 @@ export function converter(node: object | null | undefined): unknown {
106120 }
107121
108122 return properties . reduce ( ( acc , cur ) => {
109- const key = cur . key . name || cur . key . value
123+ let key = cur . key . name || cur . key . value
124+ if ( typeof key === 'string' ) {
125+ key = createSafeStringForJsonParse ( key )
126+ }
110127 // see issues#10
111128 if ( typeof key === 'number' && ! Number . isSafeInteger ( key ) ) {
112129 throw new Error ( 'Invalid syntax is included.' )
0 commit comments