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.
Related
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);
I have json file like this,
{
"data":{
"type": "runjob",
"id": "1",
"inputs": [
{
"name": "input",
"value": "d:\\My\\filestore\\JMJ\\Content\\input.xml"
},
{
"name": "cmd",
"value": "test.js //NoLogo"
},
{
"name": "output",
"value": "d:\\My\\filestore\\JMJ\\Content\\output.xml"
}
],
"disabled": false
}
}
I need to read the velues, input.xml and output.xml using javascript.. How can I get those value?
var stdin = WScript.StdIn.ReadAll();
var json = eval('(' + stdin + ')');
var log = new Log(json.data.inputs[?]);
json.data.inputs is an array (note it's json; as Tushar pointed out, you have had jason in the question). So you can use any technique for accessing or looping through an array that's supported by your environment. It look slike you're using JScript on Windows Script Host; last I checked it didn't even have ES5 features, so perhaps a simple for loop:
var i;
var inputs = json.data.inputs;
for (i = 0; i < inputs.length; ++i ){
// Here, inputs[i].name will be the name ("input", "cmd", "output")
// and inputs[i].value will be the value ("d:\\My\\filestore\\JMJ\\Content\\input.xml", for instance)
}
json.data.inputs is an array containing 3 json objects; you want the value property of the first and the third elements:
json.data.inputs[0].value; // "d:\\My\\filestore\\JMJ\\Content\\input.xml"
json.data.inputs[2].value; // "d:\\My\\filestore\\JMJ\\Content\\output.xml"
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.
What is the best way to create javascript array from json file?
I have four empty JavaScript array that I would like to populate with data imported from a json file.
var firstname = new Array();
var address= new Array();
var city = new Array();
File Json : "file.json"
[
{"name ": "John", "address": "350 Fifth Avenue", "city ": "New York"},
{"name ": "Mark", "address": "1101 Arch St", "city ": "Philadelphia"},
{"name ": "Jack", "address": "60th Street", "city ": "Chicago"}
]
I try:
$.getJSON('file.json',function (data) {
for (var i = 0; i < data.length; i++) {
firstname.push.apply( firstname, data[i].firstname );
address.push.apply( address, data[i].address );
city.push.apply( city, data[i].city );
}
});
but arrays are still empty.
Thanks in advance
================================ SOLVED ===============================
$.ajax({
async: false,
url: 'file.json',
data: "",
accepts:'application/json',
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.length; i++) {
firstname.push( data[i].firstname );
address.push( data[i].address );
city.push( data[i].city );
}
}
})
// Get arrays outside callback function
console.log('result: '+firstname.length); // result: 3
You seem to have the order wrong, data is the array so it's not
data.name[i]
but
data[i].name
and removing the strange apply it would be
$.getJSON('json.js',function (data) {
for (var i = 0; i < data.length; i++) {
name.push( data[i].name );
address.push( data[i].address );
city.push( data[i].city );
}
});
Also note that name is a bad choice for a variable name in the global context.
You have two or three problems.
Your JSON is invalid.
Remove the quotes from around the outside of it.
Seriously consider giving is a .json file extension, then you are more likely to get the right MIME type for JSON. (JSON data files are not JavaScript programs).
File Json : "data.json"
[
{"name ": "John", "address": "350 Fifth Avenue", "city ": "New York"},
{"name ": "Mark", "address": "1101 Arch St", "city ": "Philadelphia"},
{"name ": "Jack", "address": "60th Street", "city ": "Chicago"}
]
You are accessing your data in the wrong order
This is overly complicated and is accessing properties in the wrong order.
name.push.apply(name, data.name[i]);
Forget about using apply. You don't need it.
Then note that your JSON array contains the objects, not the other way around. You need to access the array index before the property name:
name.push(data[i].name);
Remember the A in Ajax
Finally - your code doesn't show how you are testing the result. Remember that Ajax is asynchronous, so that if you examine the values of your arrays outside the callback function, they might not have been populated yet.
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]);