diff --git a/json.lua b/json.lua index 711ef78..c97294e 100644 --- a/json.lua +++ b/json.lua @@ -383,6 +383,58 @@ function json.decode(str) end return res end +-- if "inline_vectors_on" is set to true, the vectors will be on the same line +-- the input is an a json string without newlines - the one generated by encode +function json.beautify (str, inline_vectors_on) + if inline_vectors_on==nil then inline_vectors_on=false end + + local str_res='' + local indent=0 + local start_line=false + in_vector=0 + for i=1 ,#str-1 do + c=str:sub(i,i) + nc=str:sub(i+1,i+1) + if c=='{' then + + str_res=str_res .. '{\n' + indent= indent+1 + start_line=true + elseif c=='}' then + if nc=="," then + str_res=str_res .. '}' + elseif nc=="}" then + indent=indent-1 + str_res=str_res .. '}\n' .. ("\t"):rep(indent) + + else + str_res=str_res .. '}\n' + end + indent= indent-1 + start_line=true + elseif c==',' then + if inline_vectors_on and in_vector >0 then + str_res=str_res .. ',' + else + start_line=true + str_res=str_res .. ',\n' + end + else + if start_line then + start_line=false + str_res=str_res .. ("\t"):rep(indent) .. c + else + if c=="[" then in_vector=in_vector+1 + elseif c=="]" then in_vector=in_vector-1 + end + + str_res=str_res .. c + end + end +end +str_res=str_res .. str:sub(#str,#str) +return str_res +end return json