output individual values from one key JSON jQuery - javascript

I'm trying to output values from an array that has one key and multiple values in a JSON file. I've managed to output the values using $.each(), but what happens is that the value is returned as an array, because it is an array! I want to output each value individually so that the output is not an array:
<img src="one-value-output" />
<img src="two-value-output" />
etc...
JSON
var dataJson = "http://www.reneinla.com/kris/scripts/print.json";
The JSON file looks like this:
{
"printImages":[
"http://reneinla.com/kris/images/print/2008-06_KZO_TEN_01.jpg",
"...",
"http://reneinla.com/kris/images/print/2008-06_KZO_TEN_03.jpg"
]
}
JAVASCRIPT
var dataJson = "http://www.reneinla.com/kris/scripts/print.json";
//var dataArr = $.parseJSON(dataJson);
$.getJSON(dataJson, function (data) {
$.each(data, function (k, v) {
console.log( v );
});
});
I'd like to be able to output each value and append it to an src attribute, but wanted to see the console.log output first.
First Question
How do you print out, console.log, all the values from the json file?
Second Question
Is this the right approach to what i'm trying to achieve? I thought I'd use a JSON file because I have 88 values that need to be appended into the DOM. I could make the JSON file into an object, in my js file, but wanted to keep it more organized and efficient. This is still fairly new, so any insight here would be appreciated. Thanks and regards!
EDIT
I was able to get my desired result using this code:
var dataJson = "http://www.reneinla.com/kris/scripts/print.json";
//var dataArr = $.parseJSON(dataJson);
$.getJSON(dataJson, function (data) {
$.each(data, function (k, v) {
var i = 0;
for (i; i < v.length; i++){
console.log( v[i] );
}
});
});
Hooray!

Looking at your JSON, what you have is an object with 1 property, which is an array of strings.
Using developer tools, you should set a breakpoint inside the $.getJSON success callback function to inspect the value of data. You'll see that data is not an array, but that you should actually be going after data.printImages. Otherwise, your code looks OK to me.
Re: Your approach. It seems like a good idea to me. Some day you might change the static .json file out for a server processed file, and you probably wouldn't have to change the client side at all to do that, other than point at a different URL.

Related

Json Keys Are Undefined When Using Them From Script Tag

I've been trying to load certain Json with Ajax GET request and then parsing it.
However when trying to access the Json key from HTML script tag it was undefined.
In order to debug this issue, I logged all the keys of Json in console as well as the Json itself. Therefore i utilized this function:
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, "); // Explanation is below
console.log(invList[0]) // Just testing with first object
console.log(Object.keys(invList[0]));
});
}
getInv();
Purpose of data.split(",, "):
Since my backend script uses different programming language, I had to interpret it to the one suitable for Javascript.
There also were multiple Json objects, So i separated them with ",, " and then split them in Javascript in order to create a list of Json objects.
After calling the function, Following output was present:
Although the interesting part is that after pasting Json object in console like this:
This was the output:
So basically, in script tag, i was unable to access object's keys, although once i used it manually in console, all keys could be accessed.
What could be the purpose behind this? It seems quite strange that different outputs are given. Perhaps invList[0] is not Json object at all in the script tag? Thanks!
data.split() returns an array of strings, not objects. You need to use JSON.parse() to parse the JSON string to the corresponding objects.
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, ");
console.log(invList[0]) // Just testing with first object
var obj = JSON.parse(invList[0]);
console.log(Object.keys(obj));
});
}
You can use .map() to parse all of them, then you'll get an array of objects like you were expecting:
var invList = data.split(",, ").map(JSON.parse);

loop in JSON with undefined elements

I am trying to figure out how to retrieve the values of a json of which i do not know the number of elements.
Example:
my json can be something like
var json = ["fixelement1":"value1","fixelement2":"value2","fixelement3":"value3","variableelement4":"value4","variableelement5":"value5"]
or
var json =["fixelement1":"value1","fixelement2":"value2","fixelement3":"value3","variableelement7":"value7","variableelement8":"value8", "variableelementN":"valueN"]
the only thing that I know is that the first 3 elements are always the same.
I use .indexOf() to search a value in fixelement3. What I would like to do is, if I find the element, I would like to retrieve the name of all the following elements (which number is variable and that are unknown) and their values.
javascript or jquery would work for me, but I have no idea..
thank you in advance!
var json ={
"fixelement1":"value1",
"fixelement2":"value2",
"fixelement3":"value3",
"variableelement7":"value7",
"variableelement8":"value8",
"variableelementN":"valueN"
}
for(prop in json){
console.log('key ======> value', prop, '=====>', json[prop]);
}

Javascript read text file and append values to array

I have a problem with populating a JavaScript array with a function...
I have some charting software that uses JavaScript. I can input my own values into an array directly to create my desired chart like so:
var data_array=[[0,170],[0,185],[0,179]]
The first value in the array corresponds to sample number (e,g, 0) and the second value corresponds to height (e.g. 170, 185 etc).
This works but I will eventually have a huge list of thousands of values. The height values will be stored in text files. There will be a different file for each sample. The text file will contain a simply list of values separated by lines.
What I need my program to do is open a text file and extract the values and then append them to the data array. So far I have this:
$.get('sample0.txt', function(data, data_array){
var lines=data.split('\n');
for (var i=0; i<lines.length-1;i++){
var item=lines[i];
data_array.push([0,item]);
}
return data_array
}
This doesn't work, although I know it is correctly extracting the values from the text file. I'm not worried about sample number as I can set this for each file. My problem is how to populate the array and make that array exist outside of the function.
I normally code in PHP and I apologize that my knowledge of JavaScript is very basic!
// set this somewhere outside of the $.get callback.
// no need to pass it in as it will be available in that scope.
var data_array = [];
$.get('sample0.txt', function(data) {
var lines=data.split('\n');
for (var i=0; i<lines.length;i++){
var item=lines[i];
data_array.push([0,item]); // modify data_array here
}
// no need to return it
});
Here's a very reduced test: http://jsfiddle.net/4GMMd/
Also note no -1 after lines.length in your for loop, unless your files end with a blank line that you don't want to read.
If I understand your question correctly, you just need to declare the data_array outside the scope of your request function. Plus, your loop is incorrect. It should be i<lines.length not lines.length-1 unless you intend to leave out the last line.
var data_array = [];
$.get('sample0.txt', function(data){
var lines=data.split('\n');
for (var i=0; i<lines.length;i++){
var item=lines[i];
data_array.push([0,item]);
}
}

Can't get JSON to output

First try at using JSON. I have an ajax/php function that returns a JSON object. Back on the js side, I can see the object and output it to a div. It looks fine. I can print it to the console, still looks good. But when I try to iterate over it and expose the individual values, I just get 'undefined' in my console. I can't figure out what I am missing. Sorry it if's something obvious, but I don't see it. Thanks!
var jsonObj = JSON.parse(xmlhttp.responseText);
console.log(jsonObj); //<--looks perfect
console.log(jsonObj.length);
document.getElementById("rightsidebox").innerHTML=response; //<--looks good
for (var group in jsonObj) {
//each of these generates 'undefined' WHY???
//I get 4 'undefined' outputs for each group, so I know that my loop is iterating correctly
console.log(group.id);
console.log(group.day);
console.log(group.time);
console.log(group.name);
}
EDIT: Here is an example of one of the JSON objects being returned by my ajax call. In this example, I only have a single object inside of the array. Of course, there will typically be multiple objects:
[{"id":"7","day":"Thursday","time":"7:00 a.m.","name":"Sub 10:00"}]
EDIT 2: Given this array, I have to ask what the point of JSON is. I can return this array without having PHP encode it in JSON format. So, if all that comes back is just a javascript array, then what have I accomplished? Why not skip the JSON encoding in PHP and then iterate over the array? Clearly there is a reason for this, so I'm obviously missing something. Is there a better way to do what I am trying to accomplish? Thanks!
Consider the following:
var myJson = '{"groupA": {"id": 123, "name": "foo"}}';
var myObj = JSON.parse(myJson);
for (var i in myObj) {
console.log(i);
console.log(i.id);
console.log(myObj[i].id);
}
The expected output here is:
myGroup
undefined
123
This is because you loop is just assigning the 'key' of your object to the value i. If you were to iterate an array, instead of an object, you'd get indices instead of strings.
In the example JSON you've given, you have an array with one object in it. If you intend to have multiple objects in your array, something like this would be better:
for (var group in jsonObj) {
var thisGroup = jsonObj[group];
thisGroup.id; // Etc etc..
}
If you have the correct jsonObj, and you say that you do, you can use formatting to output the object in an easy to read form. You don't have to loop through it.
console.log(JSON.stringify(jsonObj, null, 1));
Not sure why this works, when my original for (var group in jsonObj) loop doesn't, but whatever...
for (var i=0; i < jsonObj.length; i++) {
console.log(jsonObj[i].id);
console.log(jsonObj[i].day);
console.log(jsonObj[i].time);
console.log(jsonObj[i].name);
}

Working with a JSON file and Javascript

On return of a JSON file I can't seem to be able to detect how many results are returned. The problem seems to be with the JSON file returning a diffrent number of items each time. At times it will return 1 item, then at other it will return more than 1. You see, I'm trying to get the very first result from the JSON file so I can display it. Now, If change the code everytime I know the number that will be returned, the following two bits of code work.. Artists.id; and Artists.id[0];, but I can't seem to make them work together, at the momment..
If 1 result is returned, Artists.id; will successfully bring back the artist ID;
If more than 1 result is returned Artists.id; will return "undefined".
So I need to change it to Artists.id[0]; if the JSON file returns more than 1 item. However when I change it to this, if the JSON conatins 1 item, it will return "undefined".
It seems I need some code to tell me if the returned array has 1 or more items. I've tried arr.length but that doesn't seem to be working (perhaps i miss-coded it). I also tried if(arr===undefined) and that failed to work too. The code below is what I have come up with, using the artistzero, but it is not working. Anyone has any advice? or a reason why the code below would not work?
Current Code:
$.ajax(
{
type: "GET",
url: id_url,
dataType: "jsonp",
success: function (responseData, textStatus, XMLHttpRequest)
{
if (responseData.Artists.Artist)
{
var Artists = responseData.Artists.Artist;
var artistzero = Artists.length;
if (artistzero >= 2)
{
// if more than one result is returned
var artisttype = Artists.id[0];
}
if (artistzero <= 1)
{
// if one result is returned
var artisttype = Artists.id;
}
}
else
{
$('body').append('No results');
}
}
});
Sample JSON with 1 result:
{"Artists":{"total":"1","count":"1","start":"1","errorCount":"0","Artist":{"id":"33291476","flags":"123010","catzillaID":"0","website":"","name":"Jamie T","rating":"-1","ItemInfo":{"Relevancy":{"index":"1316"}},"hotzillaID":"1809709440","url":"http://web.com/jamie-t/","trackCount":"96"}}}
Sample JSON with more than one result:
{"Artists":{"total":"1087","count":"3","start":"1","errorCount":"0","Artist":[{"id":"256212","flags":"123523","catzillaID":"1927205428","website":"http://www.bobmarley.com/","name":"Bob Marley","rating":"-1","ItemInfo":{"Relevancy":{"index":"718"}},"hotzillaID":"1802045595","url":"http://web.com/bob-marley/","trackCount":"12706"},{"id":"312874","flags":"124611","catzillaID":"1927580000","website":"http://www.bobdylan.com/","name":"Bob Dylan","rating":"-1","ItemInfo":{"Relevancy":{"index":"694"}},"hotzillaID":"1800021697","url":"http://web.com/bob-dylan/","trackCount":"4987"},{"id":"268472","flags":"41603","catzillaID":"1927193413","website":"","name":"Bob Wills","rating":"-1","ItemInfo":{"Relevancy":{"index":"644"}},"hotzillaID":"1800264434","url":"http://web.com/bob-wills/","trackCount":"2364"}]}}
You need to access the first artist before grabbing the id (since it's an array) like this:
var artisttype = Artists[0].id;
It would be better if you could change the JSON to always return an Array, even with one result...unfortunately some platforms don't do this, for reasons beyond my comprehension.
for(var propertyname in responseData){
//will loop through the different elements in your json array
alert(responseData[propertyName]); //will output the valueof each element
}
You're right that this is problematic, and to be honest it sounds like the "other end" that's sending you the JSON is being inconsistent.
The problem is that when there are multiple items they're sending you an array for the id property, and when there's a single item they're just sending you a simple value (e.g. an integer). Ideally, when there is a single item you should be sent a single-item array - this would let you use the same array-based parsing code every time.
If you can't convince them to change what they're sending you, though, then the best bet is simply to do what you're currently doing; see if Artists.id is defined, use it if so, else fall back to accessing id as an array.
However, if more than 1 result is returned Artists.id; will return "undefined". So I need to change it to this: Artists.id[0];
this cannot be Artists.id should be "object" not undefined if Artists.id[0] exists. Maybe it is as stated Artists[0].id ? and if so you could test typeof(Artists) == typeof([])

Categories

Resources