Comparing two dictionaries

I’ve written a parser for a configuration language that turns a text file into a Xojo Dictionary. Like a good little programmer, I’m now writing a test suite.

The difficulty I’m having is comparing my generated Dictionary created with the “truth” Dictionary.

Obviously you can’t do:

If parsedDict = truthDict // Always False.

as this is doing an object reference comparison and they aren’t the same object.

I thought I’d try converting both dictionaries to JSON and then comparing those but that doesn’t work either. The issue I’m seeing here is that whilst the JSON strings look correct to me they are in different orders. Probably because Xojo’s GenerateJSON method iterates over the Dictionary and the Dictionary doesn’t guarantee the order of the keys.

My question is two-fold:

  1. Does anyone have code to compare two dictionaries for equivalency? The values in the dictionaries are only ever one of the following types: Boolean, Color, Integer, Double, String, DateTime, Nil, another Dictionary or an array. I never store class instances in the values.

  2. Does anyone know of a CLI tool or web service perhaps that can compare two different JSON strings for equivalency?

I would:

  1. loop over keys in dictionary A. And Test if they exist in Dictionary B.

  2. If so then Check if type of Value is same in Element by Key in A and Element By key in B

  3. If so then compare value in Element By Key in A and Element by key inB.

  4. If any of the above is not true then their not equal.

In the value comparer then if the Type is object then you could start with test if its same reference before proceeding in evaluating it further.

1 Like

Thanks Björn. I’ve implemented something similar but I’m getting tripped up I think by how Xojo parses JSON into a dictionary.

For example, this JSON run through ParseJSON:

{
    "ports": [8000, 8001, 8002]
}

Produces this dictionary:

Screenshot 2022-02-02 at 09.32.15

Whereas my code produces a dictionary with an Integer array. I can’t therefore compare the element types as they are different (although they are the same - both integers but mine are 64-bit and Xojo is parsing them into 32-bit).

But why put it in a JSON at all ?

I need a way to run a bunch of tests.

I figured the easiest way would be to write the “truth” as JSON and then convert that to a Xojo Dictionary which I could compare against the Dictionary my parser creates. Maybe I’m over thinking this. It just struck me as easier to write a hundred tests using JSON instead of creating complex dictionaries in Xojo code.

Found a dead simple solution on StackOverflow.

There’s a command line tool called jd that can compare two JSON strings like so:

$ jd -set A.json B.json

If there’s no output, there’s no difference.

1 Like