skip to Main Content

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


  1. Please use this. It may help you

    const jsonString1 = '{"color":"red","animal":"dog","drink":"water","food":"pizza","fish":"tuna","foo":"bar"}';
    const jsonString2 = '{"color":"red","drink":"water","food":"pizza","fish":"tuna","foo":"bar","animal":"dog"}';
    
    const regex = /^(?=.*b"animal":"dog"b)(?=.*b"fish":"tuna"b).*/;
    
    console.log(regex.test(jsonString1)); // Output: true
    console.log(regex.test(jsonString2)); // Output: true
    
    Login or Signup to reply.
  2. 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.

    jq '.animal == "dog" and .fish == "tuna"'
    

    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:

    echo '{"color":"red","animal":"dog","drink":"water","food":"pizza","fish":"tuna","foo":"bar"}' | jq '.animal == "dog" and .fish == "tuna"'
    # true
    

    If either of the key value pairs are missing, or incorrect, you’ll receive a false:

    echo '{"color":"red","animal":"cat","drink":"water","food":"pizza","fish":"tuna","foo":"bar"}' | jq '.animal == "dog" and .fish == "tuna"'
    # false
    
    echo '{"color":"red","animal":"dog","drink":"water","food":"pizza","pet":"tuna","foo":"bar"}' | jq '.animal == "dog" and .fish == "tuna"'
    # 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:

    import json
    
    
    data = json.loads('{"color":"red","animal":"dog","drink":"water","food":"pizza","fish":"tuna","foo":"bar"}')
    
    data["animal"] == "dog" and data["fish"] == "tuna"
    

    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.

    ^.*(("animal":"dog").*("fish":"tuna")|("fish":"tuna").*("animal":"dog")).*$
    

    https://regex101.com/r/qxvJu2/1

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search