regex检查json对象是否包含两个特定的KV对

gopyfrb3  于 2023-08-08  发布在  其他
关注(0)|答案(2)|浏览(107)

我试图检查JSON对象是否包含两个特定的KV对,而不管顺序如何。
例如,在下面的JSON对象中:

{"color":"red","animal":"dog","drink":"water","food":"pizza","fish":"tuna","foo":"bar"}

字符串
我想检查是否同时包含**"animal":"dog""fish":"tuna"
下面的正则表达式仅在KV对的顺序如上所述时起作用。

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


当顺序发生如下更改时,它不起作用:
{"color":"red","drink":"water","food":"pizza","fish":"tuna","foo":"bar","animal":"dog"}
我如何查询任何KV对的订单?

gijlo24d

gijlo24d1#

我不确定regex是最好的工具。当您使用json时,最好使用json专用工具。
例如,如果您可以访问jq这样的工具,您可以使用例如。

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

字符串
键值对在json中出现的顺序在这里并不重要。
查看输入数据,上面的查询将返回true

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


如果有一个键值对缺失或不正确,您将收到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

的字符串
我注意到你已经问过其他关于Python的问题,所以如果你想要一个Python的解决方案,它可以像把你的json转换成dict一样简单,然后检查键值对的存在:

import json

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

data["animal"] == "dog" and data["fish"] == "tuna"


如果你完全决定使用正则表达式(我真的不认为这是一个好的选择,但最终它是你的决定),你 * 可以 * 简单地使用|来检查两个可能的顺序,例如,

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


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

gmol1639

gmol16392#

请用这个。它可能对你有帮助

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

字符串

相关问题