What is the best way to create a form that includes both dynamic objects and dynamic arrays using a JSON schema?

I have observed how a JSON schema can be utilized to construct dynamic arrays.

My goal is to develop a JSON web form using a JSON schema that allows for objects (dictionaries) to be expandable similar to arrays.

For example, you can visit the demonstration site: .

In this demo, the schema for the form on line 69 is of type array. It includes items of type object. However, I aim to enable users of the form to define both the key and value within the form itself. This would allow me to dynamically create dictionaries. Essentially, I wish to modify line 69 from array to object, incorporate additional schema definitions indicating key properties, and generate JSON containing expandable objects.

It's possible that my struggle lies in understanding the capabilities of JSON schema. Is there a guideline within the schema definition requiring the inclusion of dynamic objects (where both the key and object structure need to be entered into the form)?

To illustrate my objective, consider the following schema:

{
  "type": "array",
  "items": {
    "type": "string"
  }
}

This schema produces:

[
  "abc"
]

What I seek is a schema that generates a form capable of producing a JSON output like:

{
  "key1": "abc",
  "key2": "xyz",
}

Where "abc" or "xyz" could be any valid JSON type or complex structure (with corresponding adjustments in the schema), and numerous key/value pairs are permitted in the object.

Therefore, the question posed is: How can I utilize a JSON schema to build a form with dynamic objects as well as dynamic arrays? Any examples of implementations are appreciated.

Answer №1

Just to confirm my understanding, are you interested in setting up Key/Value inputs as seen in this example and then enabling the user to input a custom key with its corresponding value? This data will be stored as an object inside an array and later converted to JSON. Alternatively, are you seeking to directly display JSON instead of using input fields?

var structure = {
    "$schema": "http://json-schema.org/draft-03/schema#",
    "type": "object",
    "properties": {
        "pageNum": {
            "type": "integer",
            "title": "Page Number",
            "description": "Query page number; starting from `1`. Refer to [Pagination](https://en.wikipedia.org/wiki/Pagination) for details.",
            "default": 1,
            "required": true
        },
        // Additional properties go here ...
    }
};
var FormsSetup = formsper["json-generator"];
var fs = FormsSetup.create(schema);
var containerElem = document.getElementById('container');

fs.render(containerElem, []);
<link rel="stylesheet" href='http://github.com/formsper/json-generator/tree/master/dist/css/json-gen.min.css' />
<script type="text/javascript">
// Script code goes here...
</script>
<body>

<div id="container"></div>
</body>

Answer №2

I believe the solution you are seeking is this:

{
  "type": "object",
  "patternProperties": {
    "[/w/W]": {
       "type": "object"

    }
  }
}

The usage of [/w/W] indicates that the key can have any value within your main object. Furthermore, when specifying "type" : "object", it means that the value can also be any type.

You may explore and verify this concept by visiting:

Alternatively, you can test it out at:

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

Vue.js has encountered a situation where the maximum call stack size has been exceeded

I have implemented a method called cartTotal that calculates the total price of my products along with any discounts applied, and I am trying to obtain the final value by subtracting the discount from the total. cartTotal() { var total = 0; var di ...

Unable to pass value through form submission

Having some trouble displaying data from an API on my HTML page. The function works fine when I run it in the console. <body> <div> <form> <input type="text" id="search" placeholder="Enter person& ...

I am eager to retrieve the outcome once all the queries have been completed within the loop (using express.js, react.js, and MySQL)

Currently, I am engaged in a personal project that involves using React and Express. The task at hand is to retrieve data spanning 7 days for a specific item from my database and present it in a search list. To achieve this, I attempted the following: U ...

Converting an unbroken series of string values into organized key-value pairs for easy reference

I assure you this is not a duplicated question. Despite my attempts with JSON.parse(), it seems to be ineffective. Here's the issue at hand: I recently received assistance from an answer that was both crucial and enlightening. However, the code prov ...

Insert a record at the start of a data grid - JavaScript - jQuery

What is the most effective way to use jQuery for adding a new row at the top of a table? Here is an example table structure: <table id="mytable" cellpadding="0" cellspacing="0"> <tr> <td>col1</td> ...

Node.js: Module not found error

When I run the command below to install a module from the NPM registry: npm install dc All files are successfully installed, but upon running the script dc, it fails to resolve a dependency. $ node web-test.js module.js:340 throw err; ^ Error: ...

Assistance with Validating Forms Using jQuery

I have a form located at the following URL: . For some reason, the form is not functioning properly and I am unsure of the cause. Any suggestions or insights on how to fix it? ...

Validating forms using Ajax, Jquery, and PHP, with a focus on addressing

I am currently working on processing a form using AJAX, jQuery, and PHP. However, I have encountered a 404 error while doing so. I tried searching for a solution before posting here but unfortunately couldn't find one. Below is the content of my .js f ...

The Ajax search box displays results from the most recent query

Hey there, I need some assistance with a request: var searchResults = new Array(); var ajaxRequest = function (value, type) { if (typeof(type) === "undefined") type = "default"; var ajaxData = { "title" : value, "limit" : ...

What is causing the newly generated input tags to disappear from the page?

I'm having an issue where my code successfully creates new input tags based on user input, but they disappear shortly after being generated. What could be causing this to happen? <form> <input type='text' id='input' /> ...

When making a PUT request with Fetch, the Cache-Control header is altered in Firefox but remains unchanged in

In the process of generating presigned URLs for uploading to S3, it is necessary to set the Cache-Control header value to be public, max-age=31536000, immutable. The fetch operation is executed using the following code: fetch( uploadUrl, ...

Implementing relative path 'fetch' in NextJs App Router

When attempting to retrieve data using fetch("/api/status"), the URL is only detected when utilizing the absolute path: fetch("http://localhost:3000/api/status"). This is happening without storing the path in a variable. ...

contrasts in regex special characters: .net versus javascript

Here is my current javascript implementation: EscapeForRegex = function(input) { var specials = ["[", "\\", "^", "$", ".", "|", "?", "*", "+", "(", ")", "{", "}"] for (var k in specials) { var special = specials[k]; ...

Only display PHP page content if accessed through an AJAX request, not through directly typing the URL into the address bar

Is there a way to verify if a PHP page has been accessed via an Ajax request? I'm working on a page that displays a form for updating some database data (update.php), but I only want it to be accessible if it is called by a specific page named "change ...

Rendering deeply nested data in a Vue table

I am currently in the process of updating some older code, transitioning to Vue as a replacement. Everything has been going smoothly except for one specific table that is templated using handlebars. With handlebars and nested {{each}} loops, I can easily ...

Combine strings in an array of objects

I have an array containing objects with a "Closed" property that holds numerical values. I want to loop through the array and concatenate all the "Closed" property values found in each object. For example, in the given array, the final result should be 12 ...

Utilize CSS to showcase the full-size version of a clicked thumbnail

I am working on a web page that features three thumbnails displayed on the side. When one of these thumbnails is clicked, the full-size image should appear in the center of the page with accompanying text below it. Additionally, I have already implemented ...

failure of svg spinning

I'm currently working with an SVG file and attempting to incorporate a spinning animation similar to loaders and spinners. However, I am facing an issue where the rotating radius is too large and I am struggling to control it effectively. CSS: .image ...

Understanding the Parameters for discord.js Slash Commands

I am currently working on a calculation that involves using parameters input through a slash command. While entering the parameters works without any issues, I am facing difficulty in retrieving them. The current code is resulting in an error TypeError: ...

Verify the existence of the email address, and if it is valid, redirect the user to the dashboard page

Here is the code snippet from my dashboard's page.jsx 'use client' import { useSession } from 'next-auth/react' import { redirect } from 'next/navigation' import { getUserByEmail } from '@/utils/user' export d ...