Related
This is my json format with that im displaying my array items like this.
If i have more items in my array mean how can i print that all using for loop or is there any method available to print all that items in an array?
{
"workers": [
{ "id": "5001", "type": "Basic" },
{ "id": "5002", "type": "Admin" },
{ "id": "5003", "type": "Basic" }
],
"clients": [
{ "id": "5004", "type": "Pro" },
{ "id": "5005", "type": "Basic" },
{ "id": "5006", "type": "Basic" },
{ "id": "5007", "type": "Pro" }
]
}
<script>
const api_url = "API URL";
async function get_data_from_api() {
const response = await fetch(api_url);
var data = await response.json();
var track = data["workers"][2]["id"];
document.getElementById('demo2').innerHTML = track ;
}
</script>
Reference:
JSON.stringify()
const o = {
"workers": [
{ "id": "5001", "type": "Basic" },
{ "id": "5002", "type": "Admin" },
{ "id": "5003", "type": "Basic" }
],
"clients": [
{ "id": "5004", "type": "Pro" },
{ "id": "5005", "type": "Basic" },
{ "id": "5006", "type": "Basic" },
{ "id": "5007", "type": "Pro" }
]
};
output.innerHTML = JSON.stringify(o, undefined, 2);
<pre id="output"></pre>
I am looking for a Javascript library to list the possible Json Paths based on a Json Schema.
For a json schema like below, I want to list the possible json paths.
{
"$id": "https://example.com/person.schema.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Customer",
"type": "object",
"properties": {
"firstName": {
"type": "string",
"description": "The person's first name."
},
"lastName": {
"type": "string",
"description": "The person's last name."
},
"age": {
"description": "Age in years which must be equal to or greater than zero.",
"type": "integer",
"minimum": 0
},
"address": {
"type": "object",
"city": {
"type": "string",
},
"country": {
"type": "string",
}
}
}
}
Possible Json Paths: firstName, lastName, age, address.city, and address.country
Based on #customcommander's answer
Add support for $ref (prevent recursion)
Add hierarchy parents paths too (i.e. a.b.c -> a + a.b + a.b.c)
Add support for array items (using [] as a generic indexer)
const _derivePathsFromSchema = (schema, properties, defined) => {
let paths = [];
if (!properties) return paths;
return Object.keys(properties).reduce((paths, childKey) => {
let child = properties[childKey];
const { $ref, ...childProperties } = child;
if ($ref?.startsWith('#/definitions/')) {
const definition = $ref.substr($ref.lastIndexOf('/') + 1);
if (!defined.includes(definition)) // prevent recursion of definitions
{
defined.push(definition);
child = {
...schema.definitions[definition], // load $ref properties
...childProperties, // child properties override those of the $ref
};
}
}
if (child.type === 'object') {
return paths.concat(childKey, _derivePathsFromSchema(schema, child.properties, defined.slice()).map(p => `${childKey}.${p}`));
}
if (child.type === 'array' && child.items?.properties) {
return paths.concat(childKey, `${childKey}[]`, _derivePathsFromSchema(schema, child.items.properties, defined.slice()).map(p => `${childKey}[].${p}`));
}
return paths.concat(childKey);
}, paths);
};
const derivePathsFromSchema = schema => _derivePathsFromSchema(schema, schema.properties, []);
console.log(derivePathsFromSchema({
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"BType": {
"type": "object",
"properties": {
"a": {
"$ref": "#/definitions/AType"
}
}
},
"AType": {
"type": "object",
"properties": {
"b": {
"$ref": "#/definitions/BType"
}
}
}
},
"type": "object",
"properties": {
"a": {
"$ref": "#/definitions/AType"
},
"b": {
"$ref": "#/definitions/BType"
},
"id": {
"type": "string"
},
"array": {
"type": "array",
"items": {
"type": "object",
"properties": {
"item": { "type": "string" }
}
}
},
"obj": {
"type": "object",
"properties": {
"nested": { "type": "string" }
}
}
}
}));
You don't necessarily need a library for that. You can use a simple recursive function:
var schema = {
"$id": "https://example.com/person.schema.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Customer",
"type": "object",
"properties": {
"firstName": {
"type": "string",
"description": "The person's first name."
},
"lastName": {
"type": "string",
"description": "The person's last name."
},
"age": {
"description": "Age in years which must be equal to or greater than zero.",
"type": "integer",
"minimum": 0
},
"address": {
"type": "object",
"properties": {
"city": {
"type": "string",
},
"country": {
"type": "string",
}
}
}
}
};
var path = ({properties}) =>
Object.keys(properties).reduce((acc, key) =>
acc.concat(properties[key].type !== 'object' ? key :
path(properties[key]).map(p => `${key}.${p}`)), []);
console.log(
path(schema)
);
I have the following code:
var result2 = xmljs.xml2json(response.content);
console.log(result2);
In AngularJS now I want to get value of IsError from the following JavaScript object:
{
"elements": [
{
"type": "element",
"name": "s:Envelope",
"attributes": {
"xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/"
},
"elements": [
{
"type": "element",
"name": "s:Body",
"elements": [
{
"type": "element",
"name": "ValidateLoginResponse",
"attributes": {
"xmlns": "http://tempuri.org/"
},
"elements": [
{
"type": "element",
"name": "ValidateLoginResult",
"attributes": {
"xmlns:a": "http://schemas.datacontract.org/2004/07/BeehiveHrms.MobileServices",
"xmlns:i": "http://www.w3.org/2001/XMLSchema-instance"
},
"elements": [
{
"type": "element",
"name": "a:ErrorMsg",
"attributes": [
{
"type": "text",
"text": "Please enter valid username and password."
}
]
},
{
"type": "element",
"name": "a:IsError",
"elements": [
{
"type": "text",
"text": "true"
}
]
},
{
"type": "element",
"name": "a:IsActive",
"elements": [
{
"type": "text",
"text": "false"
}
]
}
]
}
]
}
]
}
]
}
]
}
It's in:
elements[0].elements[0].elements[0].elements[0].elements[1].elements[0].text
I hope it helps!
If you don't know under which elements it is located, you need a recursive search for your JSON. Pick your favourite approach and reach the children of children of all of your nodes until you find what you are searching for.
I assumed you are always looking for "name" property. Here is the demo:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.JSON = {
"elements": [{
"type": "element",
"name": "s:Envelope",
"attributes": {
"xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/"
},
"elements": [{
"type": "element",
"name": "s:Body",
"elements": [{
"type": "element",
"name": "ValidateLoginResponse",
"attributes": {
"xmlns": "http://tempuri.org/"
},
"elements": [{
"type": "element",
"name": "ValidateLoginResult",
"attributes": {
"xmlns:a": "http://schemas.datacontract.org/2004/07/BeehiveHrms.MobileServices",
"xmlns:i": "http://www.w3.org/2001/XMLSchema-instance"
},
"elements": [{
"type": "element",
"name": "a:ErrorMsg",
"attributes": [{
"type": "text",
"text": "Please enter valid username and password."
}]
},
{
"type": "element",
"name": "a:IsError",
"elements": [{
"type": "text",
"text": "true"
}]
},
{
"type": "element",
"name": "a:IsActive",
"elements": [{
"type": "text",
"text": "false"
}]
}
]
}]
}]
}]
}]
}
// recursive function
function findNode(elem, currentNode) {
var i,
currentChild,
result;
if (elem == currentNode["name"]) { // can be a dynamic key
return currentNode;
} else {
if (currentNode["elements"]) { // can be a dynamic key
for (i = 0; i < currentNode["elements"].length; i++) {
currentChild = currentNode["elements"][i];
result = findNode(elem, currentChild);
if (result !== false) {
return result; // found
}
}
}
return false; // not found
}
}
$scope.find = function() {
var res;
res = findNode($scope.search, $scope.JSON);
if (res) {
$scope.found = angular.copy(res.elements[0]);
} else {
$scope.found = null;
}
}
$scope.search = "a:IsError";
$scope.find();
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" ng-model="search" />
<button ng-click="find()">Find</button>
<br>
<code>{{search}} : {{found}}</code>
<hr>
<button ng-click="s=!s">{{s ? 'Hide' : 'Show'}} JSON</button>
<pre ng-show="s">{{JSON | json}}</pre>
</div>
</body>
</html>
I am using node to call drafter in order to generate the json schema for an application. My goal is to get rid of all the extra output that is spit out by drafter. I end up with a huge thing of json but I only need a small portion of it.
This is what is output:
{
"element": "parseResult",
"content": [
{
"element": "category",
"meta": {
"classes": [
"api"
],
"title": "Test"
},
"attributes": {
"meta": [
{
"element": "member",
"meta": {
"classes": [
"user"
]
},
"content": {
"key": {
"element": "string",
"content": "FORMAT"
},
"value": {
"element": "string",
"content": "1A"
}
}
}
]
},
"content": [
{
"element": "category",
"meta": {
"classes": [
"resourceGroup"
],
"title": "Questions"
},
"content": [
{
"element": "resource",
"meta": {
"title": "Questions"
},
"attributes": {
"href": "/questions"
},
"content": [
{
"element": "transition",
"meta": {
"title": "List All Questions"
},
"content": [
{
"element": "httpTransaction",
"content": [
{
"element": "httpRequest",
"attributes": {
"method": "GET"
},
"content": []
},
{
"element": "httpResponse",
"attributes": {
"statusCode": "200",
"headers": {
"element": "httpHeaders",
"content": [
{
"element": "member",
"content": {
"key": {
"element": "string",
"content": "Content-Type"
},
"value": {
"element": "string",
"content": "application/json"
}
}
}
]
}
},
"content": [
{
"element": "dataStructure",
"content": [
{
"element": "Question List"
}
]
},
{
"element": "asset",
"meta": {
"classes": [
"messageBody"
]
},
"attributes": {
"contentType": "application/json"
},
"content": "[\n {\n \"question\": \"Favourite programming language?\",\n \"published_at\": \"2014-11-11T08:40:51.620Z\",\n \"url\": \"/questions/1\",\n \"choices\": [\n {\n \"choice\": \"Javascript\",\n \"url\": \"/questions/1/choices/1\",\n \"votes\": 2048\n }\n ]\n }\n]"
},
{
"element": "asset",
"meta": {
"classes": [
"messageBodySchema"
]
},
"attributes": {
"contentType": "application/schema+json"
},
"content": "{\n \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n \"type\": \"array\"\n}"
}
]
}
]
}
]
}
]
},
{
"element": "resource",
"meta": {
"title": "Question"
},
"attributes": {
"href": "/questions/{id}",
"hrefVariables": {
"element": "hrefVariables",
"content": [
{
"element": "member",
"attributes": {
"typeAttributes": [
"required"
]
},
"content": {
"key": {
"element": "string",
"content": "id"
},
"value": {
"element": "number",
"content": 1234
}
}
}
]
}
},
"content": [
{
"element": "transition",
"meta": {
"title": "Retrieve Question"
},
"content": [
{
"element": "httpTransaction",
"content": [
{
"element": "httpRequest",
"attributes": {
"method": "GET"
},
"content": []
},
{
"element": "httpResponse",
"attributes": {
"statusCode": "200",
"headers": {
"element": "httpHeaders",
"content": [
{
"element": "member",
"content": {
"key": {
"element": "string",
"content": "Content-Type"
},
"value": {
"element": "string",
"content": "application/json"
}
}
}
]
}
},
"content": [
{
"element": "dataStructure",
"content": [
{
"element": "Question"
}
]
},
{
"element": "asset",
"meta": {
"classes": [
"messageBody"
]
},
"attributes": {
"contentType": "application/json"
},
"content": "{\n \"question\": \"Favourite programming language?\",\n \"published_at\": \"2014-11-11T08:40:51.620Z\",\n \"url\": \"/questions/1\",\n \"choices\": [\n {\n \"choice\": \"Javascript\",\n \"url\": \"/questions/1/choices/1\",\n \"votes\": 2048\n }\n ]\n}"
},
{
"element": "asset",
"meta": {
"classes": [
"messageBodySchema"
]
},
"attributes": {
"contentType": "application/schema+json"
},
"content": "{\n \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n \"type\": \"object\",\n \"properties\": {\n \"question\": {\n \"type\": \"string\"\n },\n \"published_at\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"choices\": {\n \"type\": \"array\"\n }\n },\n \"required\": [\n \"question\",\n \"published_at\",\n \"url\",\n \"choices\"\n ]\n}"
}
]
}
]
}
]
}
]
}
]
},
{
"element": "category",
"meta": {
"classes": [
"dataStructures"
]
},
"content": [
{
"element": "dataStructure",
"content": [
{
"element": "object",
"meta": {
"id": "Question"
},
"content": [
{
"element": "member",
"attributes": {
"typeAttributes": [
"required"
]
},
"content": {
"key": {
"element": "string",
"content": "question"
},
"value": {
"element": "string",
"content": "Favourite programming language?"
}
}
},
{
"element": "member",
"attributes": {
"typeAttributes": [
"required"
]
},
"content": {
"key": {
"element": "string",
"content": "published_at"
},
"value": {
"element": "string",
"content": "2014-11-11T08:40:51.620Z"
}
}
},
{
"element": "member",
"attributes": {
"typeAttributes": [
"required"
]
},
"content": {
"key": {
"element": "string",
"content": "url"
},
"value": {
"element": "string",
"content": "/questions/1"
}
}
},
{
"element": "member",
"attributes": {
"typeAttributes": [
"required"
]
},
"content": {
"key": {
"element": "string",
"content": "choices"
},
"value": {
"element": "array",
"content": [
{
"element": "Choice"
}
]
}
}
}
]
}
]
},
{
"element": "dataStructure",
"content": [
{
"element": "object",
"meta": {
"id": "Choice"
},
"content": [
{
"element": "member",
"attributes": {
"typeAttributes": [
"required"
]
},
"content": {
"key": {
"element": "string",
"content": "choice"
},
"value": {
"element": "string",
"content": "Javascript"
}
}
},
{
"element": "member",
"attributes": {
"typeAttributes": [
"required"
]
},
"content": {
"key": {
"element": "string",
"content": "url"
},
"value": {
"element": "string",
"content": "/questions/1/choices/1"
}
}
},
{
"element": "member",
"attributes": {
"typeAttributes": [
"required"
]
},
"content": {
"key": {
"element": "string",
"content": "votes"
},
"value": {
"element": "number",
"content": 2048
}
}
}
]
}
]
},
{
"element": "dataStructure",
"content": [
{
"element": "array",
"meta": {
"id": "Question List"
},
"content": [
{
"element": "Question"
}
]
}
]
}
]
}
]
}
]
}
The bit below is what I need.
content = {
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"question": {
"type": "string"
},
"published_at": {
"type": "string"
},
"url": {
"type": "string"
},
"choices": {
"type": "array"
}
},
"required": [
"question",
"published_at",
"url",
"choices"
]
}
This is the code I have as of right now and it is not working the way I am envisioning. If you need any more information to help me please ask.
App.js
var fs = require('fs');
var edit = require('string-editor');
var lodash = require('lodash');
var _ = require('underscore');
const util = require('util');
const exec = require('child_process').exec;
exec('drafter -f json test.apib' , function(error, stdout, stderr) {
const json = JSON.parse(stdout);
//console.log(json)
var res
function loopThrough(obj){
for(var key in obj){
if(!obj.hasOwnProperty(key)) continue;
if(typeof obj[key] !== 'object'){
//if (cond) var x = {'$schema': };
//if (_.hasIn(obj, '$schema')) {
res = res + "\n" + (key+" = "+obj[key]);
//}
} else {
loopThrough(obj[key]);
}
}
}
loopThrough(json);
//parse = JSON.parse(test);
//string = JSON.stringify(test, null, ' ');
//string = string.replace(/\\n/g, '');
fs.writeFile('test.json', res, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
if (error !== null) {
console.log('exec error: ' + error);
}
});
This is the ouput I am down to.
undefined
element = parseResult
element = category
0 = api
title = Test
element = member
0 = user
element = string
content = FORMAT
element = string
content = 1A
element = category
0 = resourceGroup
title = Questions
element = resource
title = Questions
href = /questions
element = transition
title = List All Questions
element = httpTransaction
element = httpRequest
method = GET
element = httpResponse
statusCode = 200
element = httpHeaders
element = member
element = string
content = Content-Type
element = string
content = application/json
element = dataStructure
element = Question List
element = asset
0 = messageBody
contentType = application/json
content = [
{
"question": "Favourite programming language?",
"published_at": "2014-11-11T08:40:51.620Z",
"url": "/questions/1",
"choices": [
{
"choice": "Javascript",
"url": "/questions/1/choices/1",
"votes": 2048
}
]
}
]
element = asset
0 = messageBodySchema
contentType = application/schema+json
content = {
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "array"
}
element = resource
title = Question
href = /questions/{id}
element = hrefVariables
element = member
0 = required
element = string
content = id
element = number
content = 1234
element = transition
title = Retrieve Question
element = httpTransaction
element = httpRequest
method = GET
element = httpResponse
statusCode = 200
element = httpHeaders
element = member
element = string
content = Content-Type
element = string
content = application/json
element = dataStructure
element = Question
element = asset
0 = messageBody
contentType = application/json
content = {
"question": "Favourite programming language?",
"published_at": "2014-11-11T08:40:51.620Z",
"url": "/questions/1",
"choices": [
{
"choice": "Javascript",
"url": "/questions/1/choices/1",
"votes": 2048
}
]
}
element = asset
0 = messageBodySchema
contentType = application/schema+json
content = {
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"question": {
"type": "string"
},
"published_at": {
"type": "string"
},
"url": {
"type": "string"
},
"choices": {
"type": "array"
}
},
"required": [
"question",
"published_at",
"url",
"choices"
]
}
element = category
0 = dataStructures
element = dataStructure
element = object
id = Question
element = member
0 = required
element = string
content = question
element = string
content = Favourite programming language?
element = member
0 = required
element = string
content = published_at
element = string
content = 2014-11-11T08:40:51.620Z
element = member
0 = required
element = string
content = url
element = string
content = /questions/1
element = member
0 = required
element = string
content = choices
element = array
element = Choice
element = dataStructure
element = object
id = Choice
element = member
0 = required
element = string
content = choice
element = string
content = Javascript
element = member
0 = required
element = string
content = url
element = string
content = /questions/1/choices/1
element = member
0 = required
element = string
content = votes
element = number
content = 2048
element = dataStructure
element = array
id = Question List
element = Question
You could try running it through an online JSON schema generation tool like this: http://jsonschema.net/#/
You will also want to consider reading up on the proposed JSON Schema specification here: http://json-schema.org/documentation.html
UPDATED: If you would like to generate the schema at runtime via Node, you could leverage a module like json-schema-generator.
UPDATED AGAIN: I am not sure I follow you but, from looking at your data, you should be able to use the following to grab all content with the contentType of application/schema+json like so:
var _ = require('lodash');
var schemas = [];
function isSchemaType(contentItem) {
return _.get(contentItem, 'attributes.contentType') == 'application/schema+json';
}
function parseContent(content) {
if (_.isObject(content) && _.isArray(content.content)) {
_.forEach(content.content, parseContent);
} else if (isSchemaType(content)) {
schemas.push(JSON.parse(content.content));
}
}
parseContent(jsonData);
console.log(schemas);
Here is a working jsfiddle: https://jsfiddle.net/k7dcd6s2/
I am trying to add a sap.ui.layout.form.Form with FormContainer and FormElements to a Preview Dialog. However, my Form and its Elements doesn't get rendered.
Click Here:
{
"Type": "sap.ui.core.mvc.JSONView",
"content": [
{
"Type": "sap.m.Button",
"id": "testitemid0",
"text": "MyTestButton",
"press": "asdf"
},
{
"Type": "sap.ui.layout.form.Form",
"id": "testitemid1",
"formContainers": [
{
"Type": "sap.ui.layout.form.FormContainer",
"id": "testitemid2",
"formElements": [
{
"Type": "sap.ui.layout.form.FormElement",
"id": "testitemid3",
"label": {
"Type": "sap.m.Label",
"id": "testitemid4",
"text": "My Test Label"
},
"fields": [
{
"Type": "sap.m.Input",
"id": "testitemid5",
"value": "My Test Input",
"placeholder": ""
}
]
}
]
}
]
}
]
}
Any Idea why it doesn't render the Form?
My sap.ui.layout.form.Form-Element simply lacks a layout:
{
"Type": "sap.ui.layout.form.Form",
"id": "testitemid1",
"layout": {
"Type": "sap.ui.layout.form.GridLayout"
},
...
}
JSBin