How to do better Json parsing(IMPOSSIBLE to solve)

After carefully considering the problem ive deemed it impossible to solve due to the way regex is handeled

I am looking for a way to parse Json strings such that the nested quotes inside the JSON strings string values are automatically replaced with backslash \ " and \ ’

The issue is that when the strings are not properly formatted it causes a JSON parsing error
I am using AI to generate JSON strings for a card game. But the strings inside the generated JSON string contain these nested quotes. Which is causing parsing issues.

Ive already searched the web for solutions but it seems to be a complex issue. It was solved in python yet I am not skilled enough to convert the python functions into lua

function escape_quotes(jsonString)
--do something
end
local jsonString = [[
{
    "name": "Fiery Destruction",
    "effect": "To the hand that plays this card: You can reveal 1 "Fire" monster in your hand; add 1 'Fire' monster from your Deck to your hand."
}
]]
escape_quotes(jsonString)
--[[
Expected output:
{
    "name": "Fiery Destruction",
    "effect": "To the hand that plays this card: You can reveal 1 \"Fire\" monster in your hand; add 1 \'Fire\' monster from your Deck to your hand."
}
--]]
1 Like

You could try regex and replacing using string.gsub

string.gsub(jsonString, '"', '\\"')
and
string.gsub(jsonString, "'", "\\'")

Nope outputs { \"name\": \"Fiery Destruction\", \"effect\": \"To the hand that plays this card: You can reveal 1 \"Fire\" monster in your hand; add 1 \'Fire\' monster from your Deck to your hand.\" }

When it should be { "name": "Fiery Destruction", "effect": "To the hand that plays this card: You can reveal 1 \"Fire\" monster in your hand; add 1 \'Fire\ ' monster from your Deck to your hand." }

Oh, I misread your post, sorry. this should work:

function escape_quotes(jsonString)
	-- double quotes
	jsonString = string.gsub(jsonString, '"(.-)"', function(value)
		return '"' .. value:gsub('"', '\\"') .. '"'
	end)
	
	-- single quotes
	jsonString = string.gsub(jsonString, '"(.-)"', function(value)
		return '"' .. value:gsub("'", "\\'") .. '"'
	end)

	return jsonString
end

This function basically does the same thing as my original solution but it uses the regex pattern "(.-)" to only select text inside of double quotes.

1 Like

This is very close to the solution however it only works if the outside quote doesn’t match the inside quote.

This works:
‘His name is “Jake” lol’

This doesnt work:
“His name is “Jake” lol”

It’s probably because the regex pattern only selects double quotes, you can alter it to select single quotes.