Skip to content

Commit

Permalink
fix escape char logic in json parser
Browse files Browse the repository at this point in the history
  • Loading branch information
winsvega committed Jun 14, 2024
1 parent 16f5825 commit 006f498
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
6 changes: 5 additions & 1 deletion libdataobj/DataObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,7 @@ std::string DataObject::asJson(int level, bool pretty, bool nokey) const
out << "]";
break;
case DataType::String:
{
printLevel();
if (!m_strKey.empty() && !nokey)
{
Expand All @@ -586,22 +587,25 @@ std::string DataObject::asJson(int level, bool pretty, bool nokey) const
}

// threat special chars
char ch_before = 0;
for (auto const& ch: asString())
{
if (ch == 10)
buffer += "\\n";
else if (ch == 9)
buffer += "\\t";
else if (ch == '"')
else if (ch == '"' && ch_before != '\\')
{
buffer += "\\";
buffer += "\"";
}
else
buffer += ch;
ch_before = ch;
}
out << "\"" << buffer << "\"";
break;
}
case DataType::Double:
printLevel();
if (!m_strKey.empty() && !nokey)
Expand Down
14 changes: 11 additions & 3 deletions libdataobj/JsonParser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,18 @@ void JsonParser::checkJsonCommaEnding(size_t& _i) const
+ "around: " + printDebug(_i);
}

bool JsonParser::isEscapeChar(size_t _i) const
{
if (_i < 1)
return m_input.at(_i) == '\\';
if (m_input.at(_i) == '\\' && m_input.at(_i - 1) != '\\')
return true;
return false;
}

JsonParser::RET JsonParser::tryParseKeyValue(size_t& _i)
{
const bool escapeChar = (_i > 0 && m_input.at(_i - 1) == '\\');
if (m_input.at(_i) == '"' && !escapeChar)
if (m_input.at(_i) == '"' && _i > 0 && !isEscapeChar(_i - 1))
{
spDataObject obj;
string key = parseKeyValue(_i);
Expand Down Expand Up @@ -286,7 +294,7 @@ string JsonParser::parseKeyValue(size_t& _i) const
{
while (escapeChar)
{
escapeChar = (m_input[endPos - 1] == '\\');
escapeChar = isEscapeChar(endPos - 1);
if (escapeChar)
endPos = m_input.find('"', endPos + 1);
}
Expand Down
1 change: 1 addition & 0 deletions libdataobj/JsonParser.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class JsonParser
size_t skipSpaces(size_t const& _i) const;
std::string parseKeyValue(size_t& _i) const;
bool readBoolOrNull(size_t& _i, bool& _result, bool& _readNull) const;
bool isEscapeChar(size_t _i) const;

enum class ReadDigitType
{
Expand Down

0 comments on commit 006f498

Please sign in to comment.