简体   繁体   中英

Selecting only one random key-value pair from a particular attribute in JSON schema

How can I get a new JSON schema from the given JSON schema with only one key-value pair chosen randomly from the "properties" attribute. It should also have the "title" and "type" attributes.

{ "title": "animals object",
  "type": "object",
  "properties": {
     'cat': 'meow',
     'dog': 'woof',
     'cow': 'moo',
     'sheep': 'baaah',
     'bird': 'tweet'
  }
};

First, you can get a random number between 0-4 that can be used to get the properties key randomly and use that key to add it in the properties of new JSON object:

 var jsonSchema = { "title": "animals object", "type": "object", "properties": { 'cat': 'meow', 'dog': 'woof', 'cow': 'moo', 'sheep': 'baaah', 'bird': 'tweet' } }; var newJSON = { "title": "animals object", "type": "object", "properties":{} }; var randomNumber = Math.floor(Math.random() * 5); var randomPropertyKey = Object.keys(jsonSchema.properties)[randomNumber]; newJSON.properties[randomPropertyKey] = jsonSchema.properties[randomPropertyKey]; console.log(newJSON); 

This should do the trick:

 var originalJson = { "title": "animals object", "type": "object", "properties": { 'cat': 'meow', 'dog': 'woof', 'cow': 'moo', 'sheep': 'baaah', 'bird': 'tweet' } }; // deep copy of the json object var jsonCopy = JSON.parse(JSON.stringify(originalJson)); //gets a random property of a collection var propToKeep = pickRandomProperty(jsonCopy.properties); //deletes all properties of the copied collection except the randomly chosen one for (var key in jsonCopy.properties) { if(key.toString() !== propToKeep) { delete jsonCopy.properties[key] } } function pickRandomProperty(obj) { var result; var count = 0; for (var key in obj){ //if there's only one left, take it. if (Math.random() < 1 / ++count){ result = key; } } return result; } console.log("copy", jsonCopy); console.log("original", originalJson); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM