JSON prettifier

This is a very quick and dirty module to prettify JSON strings. Not tested throroughly!

return function(jsonStr: string, tabWidth: number?)
	local str = ""
	
	tabWidth = tabWidth or 4
	assert(tabWidth) -- for typechecking
	
	local indent = 0
	local function startNewLine()
		str ..= "\n"
		str ..= string.rep(" ", indent * tabWidth)
	end
	
	local len = #jsonStr
	for i = 1, len do
		local ch = jsonStr:sub(i, i)
		
		if ch == "{" or ch == "[" then
			str ..= ch
			indent += 1
			startNewLine()
		elseif ch == "}" or ch == "]" then
			indent -= 1
			startNewLine()
			str ..= "}"
		elseif ch == ":" then
			str ..= ": "
		elseif ch == "," then
			str ..= ","
			startNewLine()
		else
			str ..= ch
		end
	end
	
	return str
end

Example output:

{
    "Memory": {
        "PerTag": {
            "LuaHeap": "194 MB",
            "GraphicsTextureCharacter": "44 MB",
            "GraphicsSpatialHash": "0 MB",
            "Internal": "5696 MB",
            "GraphicsParts": "300 MB",
            "Sounds": "231 MB",
            "StreamingSounds": "0 MB",
            "GraphicsTerrain": "0 MB",
            "GraphicsMeshParts": "5 MB",
            "GraphicsSolidModels": "0 MB",
            "Script": "354 MB",
            "Animation": "0 MB",
            "HttpCache": "0 MB",
            "GeometryCSG": "0 MB",
            "Navigation": "0 MB",
            "Gui": "41 MB",
            "TerrainVoxels": "161 MB",
            "PhysicsParts": "1365 MB",
            "GraphicsParticles": "19 MB",
            "PhysicsCollision": "0 MB",
            "Signals": "132 MB",
            "Instances": "220 MB",
            "GraphicsTexture": "281 MB"
        },
        "Total": "6035 MB"
    },
    "Network": {
        "NetReceive": 0,
        "NetSend": 0,
        "PhysicsSend": 0,
        "PhysicsReceive": 0
    },
    "Timing": {
        "PhysicsStep": 0.2003255933523178,
        "Heartbeat": 1.867044448852539
    }
}
7 Likes

I wish this was an actual function in HttpService

3 Likes