Utilize attributes from an external JSON schema, within the identical hierarchy as the initial schema

In a separate file, I have a remote schema named "person.json".

{
    "id":"#person",
    "type":"object",
    "properties": {
        "name": {"type":"string"},
        "gender": {
            "type":"string",
            "enum":["m", "f"]
        },
        "age": {"type":"number"}
    },
    "additionalProperties": false
}

Now, my original schema is called "man.json".

{
    "id":"#man",
    "type":"object",
    "$ref":"person.json",
    "properties": {
        "beard":"boolean",
        "moustache":"boolean"
    },
    "required": ["name"],
    "additionalProperties": false
}

I am looking to integrate the properties like "name, gender" from person.json on the same level as properties like "beard, moustache" from man.json.

To demonstrate validation:

{
    name: 'John',
    gender: 'm',
    age: 29,
    beard: false,
    mustache: true
}

The goal is to validate the example above with all properties at the same level, without any nesting.

If this integration is possible, could you guide me on how to achieve it? Thank you very much.

Sincerely, João

Answer №1

To incorporate the allOf keyword into your schema, along with the use of $ref, you can do the following:

{
    "id": "/schemas/man.json",
    "allOf": [{"$ref": "person.json"}],
    ...
}

(Please note: this is specified in version 4 of JSON Schema. In version 3, it was referred to as extends.)

In simpler terms, this setup implies that every instance adhering to the Man schema must also adhere to the Person schema.

An important aspect to consider is your utilization of the additionalProperties attribute. Given that the person.json schema disallows additional properties, any instance containing a "beard" property would not be considered a valid Person. If you plan on extending the Person schema, it is recommended to remove the restriction on additional properties.

(It's worth noting that there is some disagreement within the JSON Schema community regarding this behavior, but this aligns with the current specifications.)

Answer №2

It seems that a single piece of data cannot meet the requirements of two different schemas simultaneously. In order to address this, you may have to devise a third schema that merges the two and then validate the data against it.

let personSchema = JSON.parse(personData);
let manSchema = JSON.parse(manData);

for (let prop in personSchema.properties) {
    manSchema.properties[prop] = personSchema.properties[prop];
}

let combinedSchema = JSON.stringify(manSchema);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to remove the class "active" from only one of the <li> elements using jQuery?

I am currently facing a challenge in figuring out how to remove the "active" class from just one of my lists. Here is an example of my navigation bar: <div class="container"> <ul class="nav"> <li class="active"><a href="#">& ...

Change a nested for-loop into an Observable that has been transformed using RxJS

Currently, the following function is operational, but I consider it a temporary solution as I'm extracting .value from a BehaviorSubject instead of maintaining it as an observable. Existing Code Snippet get ActiveBikeFilters(): any { const upd ...

The second function in Vue.js was unable to initialize the data field within data() due to a missing call for assistance

I have very little experience working with vue js. There are two functions that I am using: loadComponentsOfUser() and loadUserId(). The loadComponentsOfUser() function depends on the userID field being loaded by the loadUserId() function. data() { retu ...

Print JSON value to console

Can anyone help me figure out how to display specific json values in the console? Here's the script I'm working with: Promise.all([ fetch('https://blockchain.info/balance?active=3C6WPNa5zNQjYi2RfRmt9WUVux7V4xbDmo').then(resp => re ...

Synchronizing multiple file changes simultaneously in Node.js

I have a small development server set up specifically for writing missing translations into files. app.post('/locales/add/:language/:namespace', async (req, res) => { const { language, namespace } = req.params // Utilizing fs.promises l ...

Encountered an issue when deploying a Gatsby JS site on Netlify due to a non-zero exit code returned by the build script

Recently, I discovered Gatsby JS (https://github.com/gatsbyjs/gatsby) and chose to construct my portfolio website using this generator. To begin, I forked their default starter site (gatsby-starter-default) and developed my portfolio from there (https://g ...

Turn off JavaScript in the HTML submitted by users

Imagine a scenario where users can input any HTML code into their 'profile' section on a website. How can I ensure that any embedded JavaScript in this HTML does not run? Is it possible to place an infinite loop for(;;); somewhere as a preventiv ...

Expanding and collapsing multiple tables in Material-UI

I'm currently working on creating a collapsible table using MaterialUI. At the moment, all my slides have collapses but they are connected to one state for "open", so when I open one slide, all the other slides also open. Here is an example sandbox t ...

Issue with JQuery Each function not waiting for the inner function to complete

When I have this section inside an ajax function $.each(data['Result'][0], function(Key, Value) { InputGen(Value['Type'], Value['Name'], Value['Other'], Value['Value'], function(Html){ Table = ...

Is setTimeout trustworthy in Node.js environment?

My task requires me to execute multiple "setTimeouts" for 60 seconds each. Essentially, I am creating a new entry in the database and after 60 seconds, I need to verify if the database record has been modified. I prefer not to set up a complex "job queue" ...

Dividing a select option

Looking to transform a single select element into multiple select elements using the separator "/" Here is an example of the original code: <select> <option value="1234">Type 1 / Black</option> <option value="5678">Type 2 / White& ...

Troubles with implementing Gson in Android applications

Recently, I started learning Android development and came across a tutorial on how to use Gson. You can find the tutorial here. As part of my learning process, I tried to fetch a JSON object from this API link: Below is the code snippet that I used: Mai ...

Exploring the contrast between window and document within jQuery

I'm curious about the distinction between document and window in jQuery. These two are commonly utilized, but I haven't quite grasped their differences. ...

Exporting JSON data from Blender for use in Three.js

Whenever I try to export some obj models from Blender to json using the three.js plugin, it always seems to result in javascript errors on my web page. The specific error message that pops up is: TypeError: vertices is undefined This error occurs at th ...

Using tabs within a Dialog prevents the Dialog from adjusting its height automatically

Solved: Find the solution in the comments section below. I recently built a Tabs feature within a Dialog box, but ran into an issue where the height of the Dialog did not match up with the height of the tab. The problem arose when a form was placed insid ...

Attempting to conceal the select input and footer components of the Calendar component within a React application

I am currently working on customizing a DatePicker component in Antd and my goal is to display only the calendar body. Initially, I attempted to use styled components to specifically target the header and footer of the calendar and apply display: none; st ...

Utilize CSS styling on dynamically loaded HTML content

I am working on a project similar to the StackOverflow editor. I am fetching markdown text, converting it to HTML, and then displaying it in a preview area. However, when I try to style the injected HTML elements using CSS, the styles are being ignored. Up ...

JavaScript - Error: The '}' token was unexpected

Every time I attempt to move <div id="test">this should go down</div> downwards using: <div onclick="(".test").slideDown(800);">close it</div> I encounter an error whenever I click 'close it' SyntaxError: Unexpected to ...

`Troubleshooting Firebase Cloud Functions and Cloud Firestore integration`

I previously used the following Firebase Database code in a project: const getDeviceUser = admin.database().ref(`/users/${notification.to}/`).once('value'); Now, I am attempting to convert it for Firestore. My goal is to retrieve my users' ...

In mongoose, documents are able to update autonomously without any explicit request

I have encountered an issue with my verification logic. I am sending email links to users for verification, but they are getting verified even before clicking on the link. Below is the code snippet used for user registration: router.post("/register", asyn ...