How do I access a JSON array in JavaScript - javascript

I have a PHP script to which I make an Ajax request, and most of it works okay, but I'm having trouble accessing an array in the data returned to the JavaScript function.
So, the PHP has a bunch of regular variables, and one array. The array, $places, has four elements, which each have three values, as so:
[["z","815","1"],["w","2813","0"],["s","1582","2"],["b","1220","5"]]
A relevant excerpt of the PHP script is:
$encoded_places = json_encode($places); // if I don't do this then I end up with a value of "Array"
$qobject->name = "$name";
$qobject->multi = "$multi";
$qobject->places= "$encoded_places";
$myJSON = json_encode($qobject);
echo $myJSON;
In the JavaScript script (using JQuery), I successfully obtain the data from the Ajax request, and I can access all the data okay, except the $places data.
$.getJSON(url, function(data, status){
var stringified = JSON.stringify(data);
var parsedObj = JSON.parse(stringified);
var x = parsedObj.name; // alert(x); // which works fine
var myArray = new Array();
myArray.push(parsedObj.places);
for(var i = 0; i < myArray.length; i++){
console.log(myArray[i]);
}
... and the console will display what I'm expecting, namely:
[["z","815","1"],["w","2813","0"],["s","1582","2"],["b","1220","5"]]
However, I'm having difficulty accessing these values. For example, supposing I try to access the "815" portion of the first element, with something like: myArray[0][1], all I end up with is "[".
I guess somehow this whole piece of data is just a string, instead of an array, but I'm not familiar enough with JavaScript to quite know how to progress.
If, for example, I do this in the JavaScript script (hoping to see 815, 2813, 1582 and 1220 in the alerts) all I'll see is the single alert with "[". (i.e. it does the loop only once, and selects the character in position 1).
for(var i = 0; i < myArray.length; i++){
console.log(myArray[i]);
alert(myArray[i][1]);
}
I would very much appreciate someone explaining:
(a) how I can access the individual elements and values in JS
(b) how I can loop through them, although presumably once it's an array and not a string then the code above should do this.
Many thanks for any assistance.
Now Resolved:
As noted by #charlietfl, below, using quotes in
$qobject->places= "$encoded_places";
screwed things up, along with using json_encode on $places. However, without removing the quotes nothing worked either way. So, removed quotes and just used json_encode on the entire structure at the end, which now works fine.
So, the original snippet of code, given above, now looks like:
$qobject->name = $name;
$qobject->multi = $multi;
$qobject->places= $places;
$myJSON = json_encode($qobject);
echo $myJSON;

Change
$qobject->places = "$encoded_places";
To
$qobject->places = $places;
And get rid of the $encoded_places = json_encode($places); so that the one call to json_encode serializes the whole structure

Try this:
$.getJSON(url, function(data, status){
var parsedObj = JSON.parse(stringified);
console.table(parsedObj.places);
console.log(parsedObj.places)[0][0];
}
In the posted code's getJSON context, data is already a JSON string. So this line is redundantly stringifying your JSON string:
var stringified = JSON.stringify(data);
stringified is now set to a literal/escaped version of the valid JSON string from the data parameter:
[[\"z\",\"815\",\"1\"],[\"w\",\"2813\",\"0\"],[\"s\",\"1582\",\"2\"],[\"b\",\"1220\",\"5\"]]
When that double-stringified value is passed to JSON.parse for the parsedObj reference, it just becomes the original JSON string again (which looks deceptively correct in an alert box).
Strings are iterable in JavaScript, so the for loop was just going over the string.

Related

Javascript array without quotes

I've been pulling my hair out trying to figure this out.
I'm using ZingChart to plot some data from a MySQL query. I put the data into a PHP array, and then use:
var myData = <?php echo json_encode($combined); ?>;
to put it into a javascript array.
If I do:
document.write(myData[0]);
then it shows the correct value for that index. When I try to use the array with the ZingChart's JSON, I see that it puts quotes around all the data, which for some reason it doesn't like. If I manually remove the quotes using notepad, the data displays great, so I know it's just a matter of getting rid of these quotes somehow.
Here's how it looks, for example, when I view the source from the page:
var myData = [["1466766034467","71.191"],["1466766094482,71.1986"]];
I've tried many ways and spent many hours trying to get the data passed into JSON without the quotes, but I know just enough to be dangerous, so hopefully someone can guide me.
document.write(myData[1]);
will result: 1466766094482,71.1986
Thanks in advance.
Assuming you are running a reasonably current version of php you can add JSON_NUMERIC_CHECK to json_encode() options argument
json_encode($combined, JSON_NUMERIC_CHECK);
See json_encode docs
Or in javascript iterate arrays and cast values to number using any variety of methods
myData.forEach(function(arr){
arr[0] = +arr[0];
arr[1] = +arr[1];
})
You can parse the String types into Int and Float. For your 2-item arrays, the following works with the map function:
myData.map(function(x){ return [parseInt(x[0]),parseFloat(x[1]) });
// or in ES6 notation
myData.map( x => [parseInt(x[0]),parseFloat(x[1])] );
General Solution
Inspired by #charlietfl's solution, here's a generic function parseNumeric for converting all numeric data within an array. It will recurse through any nested arrays it finds.
var myData = [["1466766034467","71.191"],["1466766094482","71.1986"]];
// Convert data to numeric, including recursion within nested arrays
// Usage parseNumeric( myData );
function parseNumeric(x,y,z) {
if( Object.prototype.toString.call( x ) === '[object Array]' ) {
x.forEach(function(c,i,a){numConvert(c,i,a)});
} else if ( typeof z != 'undefined' ) {
z[y] = +x
}
}
parseNumeric( myData );
// => [[1466766034467,71.191],[1466766094482,71.1986]];

JS: encapsulated foreach loop with arrays for JSON

I'm trying to get a foreach loop in a second one.
My code:
var results = data.d.results;
var boxes= [
"Nmb1",
"Nmb2",
"Nmb3",
"Nmb4",
"Nmb5",
];
boxes.forEach(function(n){
var boxesEach = results[0].n.results;
boxesEach.forEach(function(i){
$("input[value="+'"'+i+'"'+"]").attr('checked', true);
});
});
What I'm trying to do is to make for example "Nmb1" replacing the "n" which would make the following "output code":
var boxesEach = results[0].Nmb1.results;
It works if I just put the code like that but not with the loop.
Thanks for help and tips.
BTW: I'm getting the JSON via AJAX from a Sharepoint 2013 server (with the REST API).
You need to use it like an index. This is called the bracket notation (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Bracket_notation)
var boxesEach = results[0][n].results;
The one you have right now tries to use a Dot notation for which you'd need the actual property name (i.e. Nmb1) and not a variable which holds the property name.

Pharse First Column of a text file db into php or JSON

So I am starting to learn things about JSON.
What I am trying to do is pharse the first column (id) of this txt file
http://www.ufo-history-evidence.com/myTutorials.txt
into a JSON array
As far as I know, I would have to first move it into a PHP array, and then translate to JSON.
I need to be a bit more clear about this I think,
must be JavaScript function
function executed returns a string
string is parsed as JSON, the result is an array containing IDs
This is what I got
<script type="text/javascript">
var filePath = "myTutorials.txt";
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",filePath,false);
xmlhttp.send(null);
var fileContent = xmlhttp.responseText;
var fileArray = fileContent.split('\n')
for (var i = 0, l = fileArray.length; i < l; ++i) {
fileArray[i] = fileArray[i].slice(0,7);
};
alert(fileArray.join('\n'));
</script>
Update: since the question was edited and now is clear that a Javascript solution is needed, I updated the answer match the question. I kept the original PHP functions for reference.
Well, there's little json work involved here, most of the program will handle the string processing:
obtain the contents of that file via ajax for examaple (or in PHP via file_get_contents())
split the contents of the file in lines, you can use the split() method for this (or explode() for PHP], this will generate an array filled with the lines from that file
iterate over the array from #2, and run another split() (or explode()) to break each line into the fields, add the first field into the result array
encode the result array with JSON.stringify() (or json_encode() for PHP)
Alternatively, you can use map() (or array_map() in PHP) at step #3 in order to reduce the complexity of your code.
<?php
$fh=fopen("samplie.txt","r");
if($fh){
$arr=array();
while(($line=fgets($fh))!=false){
$arr[]=explode(" ",$line);
}
$temp=array();
for($i=0;$i<count($arr);$i++){
$temp[]=$arr[$i][0];
}
echo json_encode($temp);
}
This is one way but not the most efficient one.

Read Value of JSON Result in Jquery

Here is my output of WebMethod through Ajax call:
var item=""[{\"Column1\":\"false\"}]""
There is always one row output,i-e true or false,i want to get the value of Column1,i already try Jquery.ParseJson(item),but it gives Illegal Token o error,Kindly help me how to read this value.Kindly check the inverted commas,this is the exact outcome of my web method, and this outcome and format is a necessary condition of scenario.Thanks.On using loop it gives the error:
If I understand your problem correctly, I think your extra quotes around the strings are a problem, this is invalid syntax.
This works:
var item = "[{\"Column1\":\"false\"}]";
var parsed = JSON.parse(item);
parsed.forEach(function(row) {
console.log(row.Column1);
});
console.log(parsed[0].Column1);
Here is a jsfiddle.
See here about jQuery.ParseJson vs JSON.parse, I prefer JSON.parse, but either should work fine.
In the case of older browsers without forEach use a for loop or a library like underscore.
var item="[{\"Column1\":\"false\"}]";
var parsed = JSON.parse(item);
//if forEach is not supported:
for (var i = 0; i < parsed.length; i++) {
console.log(parsed[i].Column1);
}
console.log(parsed[0].Column1);
Here is a for loop jsfiddle.
I understand that above solutions not work perfectly with your browsers, here is another alternate solution, though I know that it may not fit your scenario, but as your output is either true or false .Instead of using JsonConvert on server end, simply return the object array to client end and read value like this.
var tempo=item[0].Column1;
Not sure about the output of your service but I think you could try this:
str = 'var item=""[{\"Column1\":\"false\"}]""';
str = str.replace(/"/g, '');//remove quotes and slashes to make valid json
eval(str);//evaluate the string
console.log(item[0].Column1);

Parse response using Jquery

I have to parse a response from the server,
The response is like..
[4,"1.0",1368544417760]
[1,"Great West Road","222",1368544595000]
[1,"Ruislip Manor Station","114",1368544479000]
[1,"Bank Station / Threadneedle Street","26",1368544731000]
[1,"Belvue School","E10",1368545955000]
[1,"Brunel Road","283",1368544706000]
[1,"Annesley Avenue","303",1368545930000]
[1,"Brixton Station Road","35",1368545854000]
[1,"Southampton Row","91",1368545537000]
[1,"Camden Road Station","29",1368545008000]
[1,"Fulham Cemetery","74",1368545210000]
The response doesn't seem to like JSON or XML.
Please help me know how to parse such type of response using Jquery.
I have to update the DOM based on the response and the response is getting updated
at a regular interval automatically.
The first number may be an indicator of what sort of data is in the rest of the "array".
I'd say
parse each line as if it were JSON. It'll turn into a javascript array.
var array = JSON.parse(oneLine); // Many browsers support this.
Then pull the bits out and put them into a proper object by name. (How to do that depends on the 1st element, perhaps.)
var obj = {};
if (array[0] == 1) {
obj.station = obj[1];
obj.number = obj[2];
obj.timestamp = obj[3]; // guessing what this is, too.
}
Do whatever you need with the data object.
Put all that in a loop. Repeat until done.
There is a similar Stack Overflow question here --> converting CSV/XLS to JSON?
Looks like there are a few different possible solutions that you could look at.

Categories