使用ajv在JSON模式验证中获取`严格模式:未知关键字:“$dynamicAnchor”?

问题描述 投票:0回答:1

我正在使用 Nextjs、reactjs 和 typescript 开发一个项目。我已在网站中集成了摩纳哥编辑器,并希望根据 2020-12 草案验证用户提供的 JSON 代码。我正在使用 ajv 进行验证。 但它并没有像例外那样工作。 这是我正在使用的反应代码: 这是代码编辑器组件:

import React, { useRef, useState } from "react";
import { Editor } from "@monaco-editor/react";
import LanguageSelector from "./LanguageSelector";
import Output from "./Output";
import Ajv from "ajv";
import { LANGUAGE_VERSIONS, CODE_SNIPPETS } from "~/constants/languages";

const ajv = new Ajv();

const CodeEditor: React.FC = () => {
  const editorRef = useRef<any>(null);
  const [value, setValue] = useState<string>("");
  const [language, setLanguage] = useState<string>("json");

  const onMount = (editor: any) => {
    editorRef.current = editor;
    editor.focus();
  };
  const onSelect = (language: string) => {
    setLanguage(language);
    setValue(CODE_SNIPPETS[language]);
  };
  return (
    <div className="flex w-full">
    <div className="w-1/2">
        <Editor
        options={{
          minimap: {
            enabled: false,
          },
        }}
        height="75vh"
        width="80%"
        theme="vs-dark"
        language={language}
        defaultValue={CODE_SNIPPETS[language]}
        onMount={onMount}
        value={value}
        onChange={(value) => setValue(value || '')}
      />
      </div>
        <Output editorRef={editorRef} language={language} />
        <div><LanguageSelector language={language} onSelect={onSelect}/></div>
        </div>
          );
};
export default CodeEditor;

这是输出组件:

import React, { useState } from "react";
import * as schema from "~/_includes/draft/2020-12/schema.json";
import Ajv from "ajv"
const ajv = new Ajv() 
interface OutputProps {
  editorRef: React.RefObject<any>; // Adjust type as per your editorRef
  language: string; // Adjust type as per your language
}
const Output: React.FC<OutputProps> = ({ editorRef, language }) => {
  const [output, setOutput] = useState<string[] | null>(null);
  const sourceCode = editorRef.current?.getValue();
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [isError, setIsError] = useState<boolean>(false);
const runCode = async () => {
    const sourceCode = editorRef.current.getValue();
    // setIsLoading(true);
    if (!sourceCode) return; 
    try {
      // const sourceCode = editorRef.current.getValue();
      // if (!sourceCode) return;
      setIsLoading(true);
  
      // const validate = ajv.compile(schema);
      // const valid = validate(JSON.parse(sourceCode));
      const userSchema = JSON.parse(sourceCode); 
      const valid = ajv.validate(schema, userSchema);
      // const valid = validate(schema, sourceCode);

      if (!valid) {
        console.log("wrong");
        // throw new Error("Invalid JSON code: " + validate.errors);
        throw new Error("Invalid JSON code: ");
      }
      else{
        setOutput(["Valid JSON"]);
        console.log("correct");
      }
  
      // Proceed with code execution
      
    } catch (error: any) {
      console.error("Validation error:", error);
      setOutput([error.message]); // Display the validation error
      setIsError(true);
    } 
    finally {
      setIsLoading(false);
    }
};

  return (
    <div style={{ width: "50%" }}>
      <h2 style={{ fontSize: "1.5rem", marginBottom: "0.5rem" }}>Output</h2>
      <button
        style={{
          padding: "0.5rem 1rem",
          fontSize: "1rem",
          marginBottom: "1rem",
          backgroundColor: isLoading ? "#ccc" : "#4caf50",
          color: "#fff",
          border: "none",
          borderRadius: "4px",
          cursor: "pointer",
        }}
        disabled={isLoading}
        onClick={runCode}
      >
        {isLoading ? "Running..." : "Run Code"}
      </button>
      <div
        style={{
          height: "75vh",
          padding: "0.5rem",
          border: `1px solid ${isError ? "red" : "#333"}`,
          borderRadius: "9px",
          overflowY: "auto",
          backgroundColor: isError ? "#ffcdd2" : "#f5f5f5",
        }}
      >
        {output
          ? output.map((line, i) => <p key={i}>{line}</p>)
          : 'Click "Run Code" to see the output here'}
      </div>
    </div>
  );
};

export default Output;

我尝试使用 uri 导入 json 架构文件,并在我的项目中添加了 2020-12 草案文件。他们都给出了相同的错误

strict mode: unknown keyword: "$dynamicAnchor"

如果有人有任何建议,请帮忙。 谢谢你

reactjs next.js jsonschema json-schema-validator ajv
1个回答
0
投票

对于 2020-12,您需要导入不同的课程

import Ajv from 'ajv/dist/2020'
const ajv = new Ajv({strict:false})

我还建议使用

strict: false
的选项设置。默认情况下 (
strict:true
),Ajv 会采取一些个人自由来对不完全符合 JSON 模式规范的 JSON 模式实施附加约束。

src:https://ajv.js.org/json-schema.html#draft-2020-12

src:https://ajv.js.org/options.html#strict

© www.soinside.com 2019 - 2024. All rights reserved.