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

I am interested in redirecting command line output to a file rather than displaying it in the standard

Is it possible to use child-process and spawn in node.js to execute a command and save the output to a file instead of displaying it on the standard output? test.js const expect = require('chai').expect; const { spawn } = require('child_pr ...

Make sure two elements are siblings in JavaScript / jQuery

Looking at the HTML structure below: <div class="wrap"> <div id="a"></div> <div id="b"></div> </div> A statement is presented as false: ($('#a').parent() == $('#b').parent()); //=> false ...

Present Different Content for Visitors Using Ad-Blocking Software

I am currently working on a project that is supported by ads. These ads are subtle and relevant to the content, not obnoxious popups for questionable products. However, since the project relies on ad revenue, users with Ad Blockers unfortunately do not co ...

Spring JSON Neo4j is a powerful combination for building robust

Imagine a scenario where there is a Person node with 3 hobbies: Peter -> Hockey Peter -> Soccer Peter -> Basketball When querying the data from a string using Neo4jRepository: interface PersonRepository extends Neo4jRepository<Person, Long>{ ...

Python encountering errors while attempting to load JSON file

I have a text file containing the following json: { "data sources" : [ "http://www.gcmap.com/" ] , "metros" : [ { "code" : "SCL" , "name" : "Santiago" , "country" : "CL" , "continent" : "South America" , "timezone" : -4 , "coordinates" : {"S" : 33, "W" : ...

What is the best way to ensure that the search box automatically adjusts its position and size regardless of the screen resolution?

I'm currently working on a responsive website project and facing an issue with the absolute positioning of the search bar on the main page, which is crucial for me. Below is the code snippet: <div class="span4"> <form class="well form ...

Hot Module Replacement (HMR) for Redux Toolkit in React Native does not trigger updates in

TL;DR: Setting up the Redux Toolkit store in React Native for HMR correctly refreshes the app when changes are made, but the behavior of the reducer remains unchanged! Despite the announcement about React Native Reloading, it seems that the steps outlined ...

Is there a method to track the progress of webpage loading?

I am working on a website built with static HTML pages. My goal is to implement a full-screen loading status complete with a progress bar that indicates the page's load progress, including all images and external assets. Once the page has fully loaded ...

Adding a component dynamically with a link click in Angular: A step-by-step guide

I am encountering an issue with my web application setup. I have a navigation bar, a home page with left and right divs, and a view-associates component. My goal is to dynamically add the view-associates component into the home's right div when a spec ...

What steps should I take to extract the rendered title from this JSON data?

After trying to access the title using json["title"]["rendered"].string!, I noticed that all I was receiving was nil. [ { "title":{ "rendered":"Nachhilfe für mehrere Hauptfächer" }, "comment_status":"open", "p ...

What is the best way to modify an array within separate functions in a NodeJS environment?

I am facing an issue where I want to update an object inside the fetchAll() functions and then send it back after successful updation. However, the response I receive is '[]'. var ans = [] Country.fetchAll(newdate,(err, data) => { if ...

Automate CSS slideshow playback using JavaScript

Using only CSS, I created a basic slideshow where the margin of the element changes upon radio button click to display the desired slide. You can view the functionality in the code snippet below. Additionally, I implemented auto play for this slideshow usi ...

Prevent a function from executing using ClearTimeout()

Looking for a way to control the progress of my progress bar using two buttons. Here's the code snippet: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0 /jquery.min.js"></scr ...

Discovering the most concise string within the array

I've been working on a JavaScript program function that is supposed to return the smallest string in an array, but I keep encountering an error whenever I run it. Below is the code I have written: function findShortestWordAmongMixedElements(arr) { ...

AngularJS version 1.4.7 - Reset form to its pristine state after submitting

I have encountered an issue with my form where after submission, it appears as dirty with a red border and the submission text is missing. I attempted to resolve this by experimenting with various combinations of .$setPristine and/or .$setUntouched on line ...

Tips on when to display the "Email Confirmation" input text box only after updating the old email

Oh no!! Yes, that's exactly what I desire! I've been facing obstacles in trying to understand how to display the "Email Confirm" input text-box ONLY when the old email has been updated. Can someone point out where I might have gone wrong? :( ...

What steps should I follow to create an automatic image slider using Fancybox that transitions to the next slide seamlessly?

*I've recently ventured into web design and am currently experimenting with Fancybox. I'm interested in creating a slider with 3 images that automatically transitions to the next image, similar to what is seen on this website: Is it feasible to ...

What is the best way to include double quotation marks to create a valid JSON string in Ruby?

Whenever I send a JSON string to the third-party app, it ends up removing all the double-quotes from it. As a result, the response I get back is in this format: '{key:value, key2:value2}' This makes it impossible for me to parse the data as JS ...

Error: The page "..." contains an invalid "default" export. The type "..." is not recognized in Next.js

Currently, I have a functional component set up for the Signup page. My goal is to define props within this component so that I can pass the necessary values to it from another component. This is my current approach: export default function SignupPage({mod ...

Is there a way to make the console output more visually appealing with some styling?

What techniques do programs such as npm and firebase use to generate visually appealing and informative console output during command execution? Consider the following examples: $ firebase deploy or $ npm i <some-package> ...