Skip to content

Added beautify function #24

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions json.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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