Json架构-数组中有多个if-then子句

bpzcxfmw  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(135)

这个问题我已经研究了一段时间了,但没有找到解决办法。
Json文件遵循类似于下面的结构:

  1. [
  2. {
  3. "type": "label",
  4. "element": "text_lbl_1",
  5. "value": "Some text here"
  6. },
  7. {
  8. "type": "label",
  9. "element": "text_lbl_2",
  10. "value": 3
  11. },
  12. {
  13. "type": "image",
  14. "element": "im_url_1",
  15. "value": "https://example.com/image/kartofen.png"
  16. }
  17. ]

因此,这是一个对象列表,我希望在其中验证typevalue类型是否对齐:标签应该有一个字符串,图像应该有一个网址。
我提出的方案是:

  1. {
  2. "$schema": "http://json-schema.org/draft-07/schema#",
  3. "type": "array",
  4. "items": {
  5. "type": "object",
  6. "required": [
  7. "type",
  8. "element",
  9. "value"
  10. ],
  11. "allOf": [
  12. {
  13. "if": {
  14. "properties": {
  15. "type": {
  16. "const": "label"
  17. }
  18. },
  19. "required": [
  20. "type"
  21. ],
  22. "then": {
  23. "properties": {
  24. "value": {
  25. "type": "string"
  26. }
  27. }
  28. }
  29. }
  30. },
  31. {
  32. "if": {
  33. "properties": {
  34. "type": {
  35. "const": "image"
  36. }
  37. },
  38. "required": [
  39. "type"
  40. ],
  41. "then": {
  42. "properties": {
  43. "value": {
  44. "type": "string",
  45. "format": "uri"
  46. }
  47. }
  48. }
  49. }
  50. }
  51. ]
  52. }
  53. }

但它应该验证错误与以前的json,因为标签值不能是数字。您可以检查它here
我将在python的jsonschema实现中验证这一点,所以我正在使用draft 7。
你知道我哪里做错了吗?

thtygnil

thtygnil1#

您的模式运行良好。您刚刚将then关键字作为if的子关键字,但它们应该处于同一级别:

  1. {
  2. "$schema": "http://json-schema.org/draft-07/schema#",
  3. "type": "array",
  4. "items": {
  5. "type": "object",
  6. "required": [ "type", "element", "value" ],
  7. "allOf": [
  8. {
  9. "if": {
  10. "properties": {
  11. "type": { "const": "label" }
  12. },
  13. "required": [ "type" ]
  14. },
  15. "then": {
  16. "properties": {
  17. "value": { "type": "string" }
  18. }
  19. }
  20. },
  21. {
  22. "if": {
  23. "properties": {
  24. "type": { "const": "image" }
  25. },
  26. "required": [ "type" ]
  27. },
  28. "then": {
  29. "properties": {
  30. "value": {
  31. "type": "string",
  32. "format": "uri"
  33. }
  34. }
  35. }
  36. }
  37. ]
  38. }
  39. }

展开查看全部

相关问题