I’m trying to check whether a JSON object contains two particular KV pairs, irrespective of the order.
For example, in the JSON object below:
{"color":"red","animal":"dog","drink":"water","food":"pizza","fish":"tuna","foo":"bar"}
I want to check whether it contains both "animal":"dog"
AND "fish":"tuna"
.
The following regex works only if the order of the KV pairs are as provided above.
^.*(("animal":"dog").*("fish":"tuna")).*$
It does not work for when the order is changed as follows:
{"color":"red","drink":"water","food":"pizza","fish":"tuna","foo":"bar","animal":"dog"}
How can I check for any order of KV pairs?
2
Answers
Please use this. It may help you
I’m not sure regex is the best tool here. As you’re working with json, it’d probably be best to work with a json-specific tool.
For example, if you have access to a tool such a
jq
, you could use eg.The order in which the key-value pairs appear in the json is not important here.
See with your input data, that the above query will return
true
:If either of the key value pairs are missing, or incorrect, you’ll receive a false:
I note that you’ve asked other questions about Python, so if you want a Python solution, it can be as simple as converting your json to a dict and then checking for existence of the key-value pairs:
If you’re completely set on using regex (I really don’t think it is a good choice here, but ultimately it’s your call), you could simply use an
|
to check for both possible orders, as, eg.https://regex101.com/r/qxvJu2/1