create json array and append objects in it from form - javascript

At this moment I'm trying to create a json like this.
[
{"name": "set registry key right",
"win_acl": {
"path": "HKCU:\\Bovine\\Key",
"user": "BUILTIN\\Users",
"rights": "EnumerateSubKeys",
"type": "allow",
"state": "present",
"inherit": "ContainerInherit, ObjectInherit",
"propagation": "None"
}
},
{
"name": "Remove FullControl AccessRule for IIS_IUSRS",
"win_acl": {
"path": "C:\\inetpub\\wwwroot\\MySite",
"user": "IIS_IUSRS",
"rights": "FullControl",
"type": "allow",
"state": "absent",
"inherit": "ContainerInherit, ObjectInherit",
"propagation": "None"
}
}
]
I want to create it dynamically trough javascript.
This is what I have now:
function GenerateYaml(btn) {
$('#generatedYamlTextField').removeAttr("hidden");
var id = btn.replace("generateBtn", "");
var moduleName = $("#formpanel" + id).attr("data-title-caption");
//Looping trough panels
$("#formpanel" + id).each(function () {
var json = "[\n{\n\"name\":\"" + "module beschrijving" + "\",\n";
json += "\"" + moduleName + "\": {\n";
//Looping through labels in the panel to create the object
$('label').each(function (index, value) {
var is_last_item = (index == ($('label').length - 1));
if (!is_last_item) {
json += "\"" + value.innerText + "\":"+"\"textboxvalue\",\n";
} else {
json += "\"" + value.innerText + "\":"+"\"textboxvalue\"\n";
}
});
json += "}\n},]\n";
$("#yamltextfield").append(json);
});
}
This is what I get from above code in my textarea:
[
{
"name":"module beschrijving",
"win_acl_inheritance_module": {
"path":"textboxvalue",
"reorganize":"textboxvalue",
"state":"textboxvalue"
}
},]
My problem is that I have multiple panels and I want to add them in the same array so that I get it like the json I showed in the first place.
I hope you guys could help me out. Thanks in advance.
Greetings,
Mouaad

Don't form the json string manually. Just compose your objects, put them in an array, say arr and you can get the json string by:
JSON.stringify(arr);

Related

Pokemon JSON If Statement Issue

So I'm currently working with the PokeAPI to make a functional Pokedex.
Pokemon can have 1+ types, so I wrote an if statement to deal with that possibility by using the hasOwnProperty selector.
if (data.hasOwnProperty("types[1].type.name")) {
type.innerHTML = "Types: " + data.types[0].type.name + ", " + data.types[1].type.name;
} else {
type.innerHTML = "Type: " + data.types[0].type.name;
}
However, the code doesn't seem to work, and it defaults to the "else" portion of the if statement. Could anyone pinpoint the error in my code? Thanks!
This is an example of what the types object looks like:
"types": [
{
"slot": 2,
"type": {
"url": "https://pokeapi.co/api/v2/type/3/",
"name": "flying"
}
},
{
"slot": 1,
"type": {
"url": "https://pokeapi.co/api/v2/type/10/",
"name": "fire"
}
}
]
What you probably want to use is map, which will convert your array of objects into an array of names quite easily. You can just use this: 'Types: ' + data.types.map(t => t.type.name).join(', ') to get the snippet you want to add to the HTML. This is much simpler than mucking around with lengths or hasOwnProperty.
const data = {"types": [{"slot": 2, "type": {"name": "flying", "url": "https://pokeapi.co/api/v2/type/3/"}}, {"slot": 1, "type": {"name": "fire", "url": "https://pokeapi.co/api/v2/type/10/"}}]}
const run = document.getElementById('run')
const types = document.getElementById('types')
run.addEventListener('click', evt => {
types.innerHTML = 'Types: ' + data.types.map(t => t.type.name).join(', ')
})
<p id="types">(empty until you click "Run")</p>
<button id="run">Run</button>
When you click the button in that snippet, the data is mapped to get the names, and they're joined into your expected string. Now, if your array has three elements, or seventeen, this will continue to work.
Credit to Calvin Nunes,
Instead of using hasOwnProperty() which does not work when there are a variable number of types in the types object, it's easier to just check if there is more than 1 types with if (data.types.length > 1){}.
You're checking a string for data.hasOwnProperty
I think this might work for you:
if (data.hasOwnProperty(types[1].type.name)) {
type.innerHTML = "Types: " + data.types[0].type.name + ", " + data.types[1].type.name;
} else {
type.innerHTML = "Type: " + data.types[0].type.name;
}
This checks the actual value of types[1].type.name and not the string "types[1].type.name". Hope that helps...

Convert JSON to HTML: Uncaught TypeError: json.forEach is not a function

I want to convert JSON to HTML to display it on website. I've googled, and this error occurs when when json is a string, and first I need to parse. But when I use JSON.parse, the console says it is already an object (Unexpected token o in JSON at position 1).
$(document).ready(function() {
$("#getMessage").on("click", function() {  
$.getJSON("http://quotes.rest/qod.json", function(json) {
var html = "";
json.forEach(function(val) {
var keys = Object.keys(val);
html += "<div class = 'blabla'>";
keys.forEach(function(key) {
html += "<b>" + key + "</b>: " + val[key] + "<br>";
});
html += "</div><br>";
});
$(".message").html(html);
});
});
});
json is an object, not an array. You can use forEach only on arrays.
As you have done already, you can iterate over the object's keys like this:
Object.keys(json).forEach(function(key) {
var value = json[key];
...
});
In addition to what everyone else said, it appears that the JSON response does not look like you think it does.
var json = {
"success": {
"total": 1
},
"contents": {
"quotes": [{
"quote": "It's not whether you get knocked down, it...s whether you get up.",
"length": "65",
"author": "Vince Lombardi",
"tags": [
"failure",
"inspire",
"learning-from-failure"
],
"category": "inspire",
"date": "2016-08-09",
"title": "Inspiring Quote of the day",
"background": "https://theysaidso.com/img/bgs/man_on_the_mountain.jpg",
"id": "06Qdox8w6U3U1CGlLqRwFAeF"
}]
}
};
var messageEl = document.querySelector('.message');
messageEl.innerText = json.contents.quotes[0].quote;
<div class="message"></div>
$.getJson already transforms a JSON object into a javascript object, so you would not need to parse it again.
However, your problem starts with forEach, which is an Array method, not an Object method, therefor it will not work in your use case.
var jsonKeys = Object.keys(json); jsonKeys.forEach(...) will work, as Object.keys returns an array of Object keys.

javascript/jquery: on click copy relevant array items to new array

I think I'm missing an obvious answer. I have an array of arrays, like this
var arraylist = [
{
"id" = 0,
"title" = "title number 1",
"info" = "some info etc 1"
},
{
"id" = 1,
"title" = "title number 2",
"info" = "some info etc 2"
},
]
...etc. And a function that makes some html from each array, which is appended to a ul element.
function makeBox(){
for (i = 0; i < arraylist.length; i++ ) {
var boxHTML = '<li id="' + arraylist[i].id + '">'
+ '<div>' + arraylist[i].title + '</div>'
+ '</li>'
$('ul').append(boxHTML);
};
};
Now using a click function, on clicking the 'li' I want the relevant array from arraylist to be copied to a new array.
newArrayList = []
So clicking on li #0 would copy the first array from 'arraylist' to the 'newArrayList'.
I will then be making different HTML from 'newArrayList' using different values. So in the makeBox function I won't show the value "info", but when I make HTML from newArrayList I will.
I could use innerHTML to get the data back out of the HTML to the newArrayList, but would have to append "info" to a hidden span, or something. This seems like the long way round. So what's the easy way?
I'm just learning so go easy on me. Also did a good search and couldn't find the answer. If it's already there please direct me politely.
So a few notes:
It's not an array of arrays. It's an array of objects. The [ ] block
is an array. The { } is an object.
The $('ul') will select ALL uls on the page, not necessarily just the
one you intend.
The object structure is incorrect, it should be using colon (:) rather
than equal (=) characters. It should look more like this:
var arraylist = [{
"id": 0,
"title": "title number 1",
"info": "some info etc 1"
}, {
"id": 1,
"title": "title number 2",
"info": "some info etc 2"
}]
Here is a modified version of your function.
function makeBox(){
var $ul = $('ul.from_array_one');
for (var i = 0; i < arraylist.length; i++) {
var item = arraylist[i];
var $boxHTML = $('<li id="' + item.id + '">' + item.title + '</li>');
$boxHTML.click(onSelectItem(item));
$ul.append($boxHTML);
};
};
Where a new function exists accepting the array object item, such as:
function onSelectItem( item ){
return function(){
var $ul2 = $('ul.from_array_two');
var $boxHTML2 = $('<li id="' + item.id + '">' + item.info + '</li>');
$ul2.append($boxHTML2);
}
}
Shaun's solution should work when implemented correctly (one point for your effort).
Here is another way.
I modified your (OP's) function so can be reused for other array of same types. Since you're learning, I encourage you to read up on DRY principle a.k.a. "don't repeat yourself". Adhering to this principle while designing your code, will help you write code that is more reusable resulting in shorter code, in the longer run a more maintainable code base. And in the process you will become an even better coder.
var arraylist = [
{
"id": 0,
"title": "title number 1",
"info": "some info etc 1"
},
{
"id" : 1,
"title": "title number 2",
"info": "some info etc 2"
},
];
var newArrayList = [];
///
function makeBox(arrayToMake, ulToAppendTo, liClass){
for (i = 0; i < arrayToMake.length; i++ ) {
var boxHTML = '<li class="'+liClass+'" id="' + arrayToMake[i].id + '">'
+ '<div>' + arrayToMake[i].title + '</div>'
+ '</li>'
$(ulToAppendTo).append(boxHTML);
};
};
var firstListClass = "first_list_item";
var secondListClass = "second_list_item";
makeBox(arraylist,'.ul_one',firstListClass);
$("."+firstListClass).click(function(){
copyArray(arraylist,newArrayList);
makeBox(newArrayList,'.ul_two',secondListClass);
});
function copyArray(sourceArray, targetArray)
{
sourceArray.forEach(function(item){
//for demo purpose only
item.title="new title " + item.id;
targetArray.push(item);
});}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>first array result</p>
<ul class='ul_one'></ul>
<p>new array result</p>
<ul class='ul_two'></ul>

How to pass JSON value into a variable / function?

I am currently parsing a json file and appending the data to an HTML table. I need to create a few variables that equal 3 of the properties within my JSON object. And I need to include those variables in a function that I am appending to one of the td elements within the table for each of my JSON objects.
Here is my function to append the data...
function createPatientTable(json) {
$.each(json.LIST, function(i, COPD_QUAL) {
$('.footable > tbody:last').append('<tr><td>' + COPD_QUAL.PATIENT + '</td><td>' + COPD_QUAL.FIN + '</td><td>' + COPD_QUAL.NURSE_UNIT + '</td><td>' + COPD_QUAL.ROOM + '</td><td>' + COPD_QUAL.BED +'</td><td>' + COPD_QUAL.ATTENDING_PHYS + '</td><td>' + COPD_QUAL.LENGTH_OF_STAY + '</td><td class="assessment ' + getSeverity(COPD_QUAL.MED_ASSESS) + '" onclick="openPowerform">' + COPD_QUAL.MED_ASSESS + '</td></tr>');
});
$('.footable').footable();
};
Here is one of my JSON objects (formatted for readability):
{
"COPD_QUAL":15,
"LIST":[
{
"PATIENT": "TEST, TRICKLE",
"FIN": "70100905",
"NURSE_UNIT": "TIC",
"ROOM": "C219",
"BED": "A",
"ATTENDING_PHYS": "LEVITEN , DANIEL L",
"LENGTH_OF_STAY": "171days 02:14:15",
"MED_ASSESS": "Mild exacerbation",
"ACTIVITY_ID": "305675472.0000",
"PERSON_ID": 8986122.000000,
"ENCNTR_ID": 14150574.000000
}
]
}
I need to plug COPD_QUAL.PERSON_ID, COPD_QUAL.ENCNTR_ID, and COPD_QUAL.ACTIVITY_ID into my below function so when the td element is clicked, the below function triggers with the personid, encntrid, and activityid of the JSON object that has been appended to that row:
function openPowerform() {
var dPersonId = "COPD_QUAL.PERSON_ID";
var dEncounterId = "COPD_QUAL.ENCNTR_ID";
var formId = 0.0;
var activityId = "COPD_QUAL.ACTIVITY_ID";
var chartMode = 1;
var mpObj = window.external.DiscernObjectFactory("POWERFORM");
mpObj.OpenForm(dPersonId, dEncounterId, formId, activityId, chartMode);
};
How can I successfully make these variables "dynamically" equal my JSON values? (since the values are different per object/string within my JSON file).
Thanks in advance!
Your JSON is mal-formed. Here is a valid object:
{
"COPD_QUAL": 15,
"LIST": [
{
"PATIENT": "TEST, TRICKLE",
"FIN": "70100905",
"NURSE_UNIT": "TIC",
"ROOM": "C219",
"BED": "A",
"ATTENDING_PHYS": "LEVITEN , DANIEL L",
"LENGTH_OF_STAY": "171days 02:14:15",
"MED_ASSESS": "Mild exacerbation",
"ACTIVITY_ID": "305675472.0000",
"PERSON_ID": 8986122,
"ENCNTR_ID": 14150574
}
]
}
Each object within the LIST array has to be addressed by its array position. With this object, your object property references would be:
LIST[0].PERSON_ID, LIST[0].ENCNTR_ID, and LIST[0].ACTIVITY_ID
I don't know if this is how you want to structure your JSON in the end, but this is what you have now. Also, there is no absolute need to run this through JSON.parse(). It can be treated like a JavaScript Object Literal and accessed the same way.

How to find the right Json object

I am new to Json and trying to load a part of a Json object. The structure is:
{
"Monday": {
"title": "Magic Monday",
"text": "On Magic Monday, all the food disappears.",
"image": "images/special.jpg",
"color": "red"
},
"Tuesday": {
"title": "Twofer Tuesday",
"text": "Two vegetables for the price of one!.",
"image": "images/special.jpg",
"color": "green"
}
}
I have a variable, weekDay, which I am going to use to find the right object. When this is found, I want to use the value of title and text in my HTML.
So far I have the code:
$.getJSON('data/specials.json', function (data) {
$.each(data, function (entryIndex, entry) {
var html = '<h4>' + entry['title'] + '</h4>';
html += '<p>' + entry['text'] + '</p>';
$('#details').append(html);
});
});
But I do not know, how to only get the title and the text from the object with the right weekday.
Thanks in advance :)
If you have
var weekDay = "Tuesday";
then you can simply use
var entry = data[weekDay];
and then
var title = entry.title;
or
var title = entry['title'];
This document explains how you access object properties.

Categories

Resources