How to find the right Json object - javascript

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.

Related

create json array and append objects in it from form

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);

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>

Looping Simple JSON Array

For some reason my loop is treating this array as a string and looping through each character.
Here's the structure:
var json = [
{
"featured": "1",
"href": "someurl/",
"property": "some property",
"location": "<strong>Winston-Salem</strong>North Carolina, United States",
"date": "23 Oct",
"year": "2014"
},
{
"featured": "1",
"href": "someurl/",
"property": "Sheraton Albuquerque Airport Hotel",
"location": "<strong>Albuquerque</strong>New Mexico, United States",
"date": "23 Oct",
"year": "2014"
}
]
I'm looping it with:
for(var i = 0; i <= json.length; i++) {
console.log(json[i]);
}
Here's a snippet of the type of output I get:
f
e
a
t
u
r
e
d
"
:
"
1
"
Json is actually a string while you havent serialized it. So it is a string representation of arrays lists and other objects.
If it is an ajax response maybe you have a wrong mime type. So it thinks it is getting a raw string rather than json.
If you are asking such a question I think you probably should read this first JSON
Edit:
If you want to get correct answer you should clarify your question. For example what are you using to get json.
If it is jQuery than you shuld use something like this:
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
took it from here
or if you are using pure js you should manually serialize json like this:
var obj = JSON.parse(text);
took it from here
where text variable contains string got from the server or wherever you get it from.

getJSON to fetch data from this json array

This is a sample json array from my code. How can i use getJSON to fetch data from this array.
"Restoration": [
{
"Easy": {
"value": "1",
"info": "This is Easy."
},
"Medium": {
"value": ".75",
"info": "This is Medium."
},
"Difficult": {
"value": ".5",
"info": "This is Difficult."
}
}
]
using jQuery jQuery.getJSON():
$.getJSON('ajax/test.json', function(data) {
console.log(data); //see your data ( works in Chrome / FF with firebug)
console.log(data["Restoration"][0]["easy"]["value"]) //should output 1
});
This is an alternative to use "jQuery.getJSON()" because sometimes we don't have a "domain/file.json" or somewhere to do the $get or we don't want to use jQuery
for this simple process.
This method parses json from string.
You can do it with simple javascript like this:
//json string for testing
var jsonstr = '{"id":"743222825", "name":"Oscar Jara"}';
//parse json
var data = JSON.parse(jsonstr);
//print in console
console.log("My name is: " + data.name + " and my id is: " + data.id);
Hope this helps.
Regards.
This might help you.
http://underscorejs.org/#keys
var list=_.Keys(data["Restoration"][0]);

Categories

Resources