StrictJson Is a JSON Library That Accepts Only JSON

Some JSON readers accept a comma after the last item. Some accept 01, TRUE in capitals, .5, or a second document glued on after the first. They read it anyway and hand back their best guess, which is a generous thing to do with the file that decides your lot size.

StrictJson doesn’t guess. It’s one free include file for MQL5 and MQL4 on the MQL5 CodeBase, and it turns JSON text, UTF-8 bytes or a file into a tree you read by key, by list position or by a dotted path like panel.theme. The tree goes back out on one line or indented, to a string or to a file. Expert advisors and scripts need that for settings files, for whatever a WebRequest brought back, and for JSON bodies to send. The rules are RFC 8259, the document that defines JSON. Anything outside it comes back as an error with a line and a column, and that’s the entire personality.

Installing it

There’s an entry for MetaTrader 5 and one for MetaTrader 4, and both ship the same StrictJson.mqh, which includes no other file. In the terminal’s data directory it lives at MQL5\Include\StrictJson\StrictJson.mqh, or MQL4\Include\StrictJson\StrictJson.mqh on MetaTrader 4. Your program pulls it in with one line:

#include <StrictJson\StrictJson.mqh>

Each zip also carries StrictJsonExample, a script, the same one in both entries apart from a comment. It belongs in MQL5\Scripts or MQL4\Scripts. Compiled in MetaEditor and attached to a chart, it writes its whole demonstration to the Experts tab: it saves a settings file and loads it back, reads a text by path, feeds the parser six texts that are not JSON, and round-trips a few values that other code likes to mangle.

Reading a value

Parse(text, error) returns JSON_OK or an error code, and puts the reason in error. The example parses this:

#define EXAMPLE_SETTINGS "{\"symbol\": \"US500\", \"lots\": 0.01, \"days\": [\"Mon\", \"Wed\", \"Fri\"], \"alerts\": {\"push\": true}}"

and reads it like this:

   PrintFormat(
      "read symbol=%s lots=%.2f days=%d first_day=%s push=%s max_spread=%d",
      settings.GetString("symbol"),
      settings.GetDouble("lots"),
      settings.Get("days").Size(),
      settings.GetString("days.0"),
      BoolText(settings.GetBool("alerts.push")),
      settings.GetInt("max_spread", EXAMPLE_SPREAD_FALLBACK)
   );

days.0 is the first item of the days list and alerts.push is a member inside a member. GetString, GetDouble, GetLong, GetInt and GetBool all take a fallback and return it when the path is missing or holds another type. The text has no max_spread, so the last call quietly returns 30. GetInt also falls back when the number doesn’t fit an int.

To get the node itself, Get(key) and At(index) go one level down and Find(path) follows a whole path. All three return NULL for a missing part. Find splits on the dot, which leaves a key with a dot in its name reachable only through Get. Whoever put a dot in a key name had it coming. Size, KeyAt and Has walk an object, and Type(), IsNull(), IsString() and the other Is checks tell you what you’re holding.

Text that is not JSON

Six texts from the example, each of them JSON if you squint:

   string texts[] = {"[1,]", "[01]", "TRUE", "[.5]", "{\"a\" 1}", "{\"a\": 1}\n{\"b\": 2}"};

A real run printed this for the first five:

refused text=[1,] error="line 1 column 4: unexpected character"
refused text=[01] error="line 1 column 3: expected ',' or ']'"
refused text=TRUE error="line 1 column 1: unexpected character"
refused text=[.5] error="line 1 column 2: unexpected character"
refused text={"a" 1} error="line 1 column 6: expected ':'"

The sixth, two documents on two lines, gets line 2 column 1: unexpected text after the value. [01] fails at column 3 because a JSON number can’t start with a leading zero: the parser ends the number at the 0, then wants a comma and finds a 1. I ran the parser against JSONTestSuite, a public set of 318 test files for comparing JSON readers. Of the 95 it must accept it accepts 95, and of the 188 it must refuse it refuses 188. Boring numbers. That’s the point.

A failed Parse leaves the value you parsed into exactly as it was. The parser builds into a scratch value and moves it over only on success. Your good settings stay in memory and the broken file goes nowhere.

Calls that can fail return JSON_OK or one of seven JSON_ERROR_ codes, numbered in MQL’s user error range, and the file calls can also hand back the terminal’s own code untouched. StrictJsonErrorText(code) turns any of them into a short English line. The library itself prints nothing. Your Experts log is yours to clutter, not its goddamn hobby.

More than 512 levels of nested objects and arrays fails with JSON_ERROR_LIMIT, and so does a number too large for a double. A duplicate key keeps the last value. A \u0000 escape ends the string right there, because an MQL string can’t hold a NUL character. The parser still checks the rest of that string for errors, out of principle.

Numbers

round trip text={"price":0.1,"id":9223372036854775807,"none":null,"empty":"","obj":{}}

0.1 goes out as 0.1. Not as 0.10000000000000001, which would then sit in your settings file for the rest of its fucking life. The writer picks the fewest digits that read back as the same double. From 0.0001 up to just under 1e16 it writes plain decimals, always with a fraction, so a double of 100 comes out as 100.0. Outside that range you get 1e+16 and friends. -0.0 stays -0.0, for the three people who care.

A number written without a fraction or exponent is kept as a 64-bit integer, which is how 9223372036854775807 survives the trip above. One bigger than that becomes a double. IsInteger() tells you which you got, and AsLong cuts a fraction toward zero. The same rule bites on the way out: PutLong writes 30, PutDouble on the same 30 writes 30.0. Both are correct.

NaN and infinity have no JSON form. SetDouble stores them anyway. Serialize then refuses the whole document with JSON_ERROR_NOT_FINITE and leaves your output string alone, and ToString returns an empty string.

null, an empty string, an empty array and an empty object stay four different things. This shouldn’t need saying. An object keeps its keys in the order they were added.

Building a document

From the example’s settings class:

      doc.SetObject();
      doc.PutDouble("lots", m_lots);
      doc.PutLong("max_spread", m_maxSpread);
      CJsonValue *alerts = doc.Set("alerts").SetObject();
      alerts.PutBool("push", m_alertPush);
      alerts.PutBool("sound", m_alertSound);

Set(key) returns the member for you to fill, Append() adds an array item, and the Put and Add calls set a value in one go. Every Set method returns the value it changed, so calls chain. On a null value, Set and Append first turn it into an object or an array. On anything else they return NULL, and your number stays a number. A key that already exists keeps its place in the order when you set it again. Remove, RemoveAt and CopyFrom delete members and make deep copies.

Serialize(out, indent, ensureAscii) writes the text. Indent 0 is one line with no spaces. Indent 2 is one value per line, two spaces per level. ensureAscii writes every non-ASCII character as a \uXXXX escape, for whatever creaky shit on the other end still can’t read UTF-8.

Files

   int err = doc.SaveFile(EXAMPLE_FILE, EXAMPLE_INDENT);
   if(err != JSON_OK)
     {
      PrintFormat("settings save failed path=%s err=%d desc=\"%s\"", EXAMPLE_FILE, err, StrictJsonErrorText(err));
      return;
     }

SaveFile(path, indent, commonFlag) and LoadFile(path, error, commonFlag) work under MQL5\Files, or MQL4\Files on MetaTrader 4. With FILE_COMMON they use the Files directory all terminals share. SaveFile indents by 2 unless told otherwise and creates the directories in the path, split on backslashes. It writes the text to the path plus .tmp and then moves that over the real file. Until the new file is complete, the old one stays whole.

When the file is read back, a missing key keeps the value it already had. An older file without a newer setting still loads:

      m_lots = doc.GetDouble("lots", m_lots);
      m_maxSpread = doc.GetInt("max_spread", m_maxSpread);
      m_alertPush = doc.GetBool("alerts.push", m_alertPush);

LoadFile returns JSON_ERROR_NOT_FOUND for a missing file, which on a first start is just Tuesday. Files are UTF-8 both ways. A leading byte order mark is dropped. The usual encoding crap fails with JSON_ERROR_ENCODING and the byte offset: NUL bytes, overlong forms, encoded surrogates, cut sequences. ParseUtf8(bytes, error) does the same for the bytes a WebRequest hands you, and StrictJsonEncodeUtf8 turns your text into bytes for the request body.

On MetaTrader 4 the calls and the output are the same. The one MQL4 difference is handled inside the file. MQL4’s StringSubstr reads a length of 0 as “to the end of the string”, which is an odd way to hear “nothing”, so the library never asks it for an empty piece.

StrictJson example output on MetaTrader 5: the saved settings.json file on top, the Experts log with the loaded settings, the refused texts and the round trip below
The settings file it wrote, then the Experts log: settings loaded back, six texts refused with line and column, numbers and empties kept as they were. MetaTrader 5.

Who owns what

A CJsonValue owns its children and deletes them. Pass it by reference, and use CopyFrom when you want a real copy. The pointers that Get, At, Find, Set and Append return belong to the document, not to you, so keep your delete the hell away from them. They stay valid until that part is removed or replaced, or the document goes away.

It reads JSON, and nothing that only looks like it.

StrictJson is a free download from the MQL5 CodeBase for MetaTrader 5 and MetaTrader 4.