I'm revising code written by another developer. Here he collects values and turns them from an array (dataId) into a comma-separated string:
$("#retrieve_works_form").on('submit', function(e) {
e.preventDefault();
$('#toggle_search_terms').trigger('click');
var dataId = new Array();
$('li.nw').each(function() {
var thisDataId = $(this).attr('data-id');
dataId.push(thisDataId);
});
$('li.added_gallery_item').each(function() {
var thisDataId = $(this).attr('data-id');
dataId.push(thisDataId);
});
$('#returned_gallery_work_ids').val(dataId.join(','));
The $_POST['returned_gallery_work_ids'] therefore holds a comma-separated string of the values in the dataId array. I want to revise this so it simply returns the array, with each element in a sequential index. I would think that doing this would do the trick:
$('#returned_gallery_work_ids').val(dataId);
...but it doesn't; it returns a comma-separate string of values, no different than what is returned when dataId.join(',') is the argument of the .val() operator.
There are really two questions here:
Why is the result a comma-separated string in each case?
How do I make it return the dataId array?
[The second question is the truly necessary question, but I want to understand the mechanics of what's taking place here.]
When storing a value of any kind in an input, it's stored as a string, so if you later retrieve it, you'll need to split it:
var galleryArray = $("#returned_gallery_work_ids").val().split(',');
Or in PHP on the server side, you'll use this:
$galleryArray = explode( ",", $_POST['returned_gallery_work_ids'] );
Hope this helps.
Following is my json object produced using php script
$to_encode[]= mysql_fetch_assoc($result);
echo json_encode($to_encode);
and the output is
[{"wid":"2","repid":"1"}]
to extract values of wid and repid I used below given code in js
var obj = JSON.parse(data);
var a = obj.["wid"];
var b = obj.["repid"];
but I'm getting value for a and b as undefined instead of 2,1
Looks like your JSON encodes not simply one object, but an array containing one object. But that array doesn't have the wid and repid properties, only the object inside the array has!
Try
{"wid":"2","repid":"1"} to encode just an object without putting it into an array or
obj[0]["wid"] to access the properties of the first (and only) object in the array.
By the way, if you know the names of the properties, you should use dot notation: obj[0].wid instead of obj[0]["wid"].
Your json object is actually an array of objects (in this case there only is one object: {"wid":"2","repid":"1"}).
This should work
var obj = data[0] //access the first element of the json array
var a = obj.wid;
var b = obj.repid;
Try using obj[wid]. Array have wid as key and 2 as a value.
I have a PHP array that has a table id as the key and a table field as the value.
Example PHP:
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$array[$id] = $row['some_field'];
}
I then use json_encode($array) to get something like:
{"id1":"value1","abc":"123","xyz":"789"}
How can I loop through this in jQuery? From what I have found so far it seems like I need to know the key. So:
var obj = jQuery.parseJSON(jsonVar);
alert(obj.abc); //prints 123
But how can I get these values if I don't know the keys since they are dynamic?
Do I need to restructure my PHP array?
Once you encode an associative array in php into a JSON object it is no longer an array, it is an object with keys and values. You can iterate through them in javascript using for..in
for (var key in obj) {
console.log(obj[key]);
}
Note: for..in does not garuntee order, if you need to ensure order you will have to make your array indexed, instead of key=>value, and use a for loop (or while) instead.
You can get the keys of your array using Object.keys, then loop through them. Unlike for...in, this gives you the option to .sort() the keys before processing them:
var keys = Object.keys(obj).sort(); // sorting is optional
for (var i=0; i<keys.length; i++) {
var key = keys[i],
val = obj[key];
console.log(key+":"+val);
};
In older browsers, you'll need a polyfill to enable the Object.keys method. MDN has one on their documentation page.
I receive from the server a JSON like the following:
{"0":{"0":"image1.jpg","1":"texthere","2":"0"},"1":{"0":"image66.jpg","1":"texthere","2":"1"},"2":{"0":"image12.jpg","1":"texthere","2":"2"},"3":{"0":"image44.jpg","1":"texthere","2":"3"},"4":{"0":"image34.jpg","1":"texthere","2":"4"},"5":{"0":"image33.jpg","1":"texthere","2":"5"},"6":{"0":"image21.jpg","1":"texthere","2":"6"},"7":{"0":"image32.jpg","1":"texthere","2":"7"},"8":{"0":"image13.jpg","1":"texthere","2":"8"},"9":{"0":"image11.jpg","1":"texthere","2":"9"},"10":{"0":"image03.jpg","1":"texthere","2":"10"},"length":"12"}
The developer who coded this used JSON_FORCE_OBJECT as a parameter of the json_encode method in PHP.
In JavaScript is there any "magics" (that is, not a custom function) to convert this structure to a multidimensional array?
I would want something like:
[["image1.jpg","texthere","2"],["image66.jpg","texthere","1"]]...
Disclaimers:
- I'm looking for a native implementation (not JQuery);
- The PHP can be eventually changed (if needed);
Any help is appreciated, thanks in advance.
The easiest way I can think of to do what you want is to use regular expressions to convert the JSON from object literals to array literals.
Unfortunately, Simon Cowell is more magical than this approach.
//I don't know why you don't want a custom function.
function dataToArray(data)
{
data = data.replace(/"[0-9]+":/g,""); //Remove all index keys
data = data.replace(/,"length":"[0-9]+"/g,""); //Remove length key-value pair
data = data.replace(/{/g,"["); //Change the left brackets
data = data.replace(/}/g,"]"); //Change the right brackets
return JSON.parse(data);
}
Not magic, but you can loop over the data and test what type of value it has.
A basic example would be as follows. It doesn't have the error checking I'd want in production code though.
var data = {"0":{"0":"image1.jpg","1":"texthere","2":"0"},"1":{"0":"image66.jpg","1":"texthere","2":"1"},"2":{"0":"image12.jpg","1":"texthere","2":"2"},"3":{"0":"image44.jpg","1":"texthere","2":"3"},"4":{"0":"image34.jpg","1":"texthere","2":"4"},"5":{"0":"image33.jpg","1":"texthere","2":"5"},"6":{"0":"image21.jpg","1":"texthere","2":"6"},"7":{"0":"image32.jpg","1":"texthere","2":"7"},"8":{"0":"image13.jpg","1":"texthere","2":"8"},"9":{"0":"image11.jpg","1":"texthere","2":"9"},"10":{"0":"image03.jpg","1":"texthere","2":"10"},"length":"12"};
function data_to_array(data) {
var array = [];
for (var key in data) {
var value = data[key];
if (typeof value === 'string') {
array[key] = value;
} else {
array[key] = data_to_array(value);
}
}
return array;
}
var array = data_to_array(data);
console.log(array);
Make sure you add hasOwnProperty checks if your object prototypes might be messed with. You should probably also add a check to make sure that only integer keys are added to the array.
There is no built-in functions. If you have JSON string, you can do string replacement, otherwise you have to loop as shown below.
var dataObject = {"0":{"0":"image1.jpg","1":"texthere","2":"0"},"1":{"0":"image66.jpg","1":"texthere","2":"1"},"2":{"0":"image12.jpg","1":"texthere","2":"2"},"3":{"0":"image44.jpg","1":"texthere","2":"3"},"4":{"0":"image34.jpg","1":"texthere","2":"4"},"5":{"0":"image33.jpg","1":"texthere","2":"5"},"6":{"0":"image21.jpg","1":"texthere","2":"6"},"7":{"0":"image32.jpg","1":"texthere","2":"7"},"8":{"0":"image13.jpg","1":"texthere","2":"8"},"9":{"0":"image11.jpg","1":"texthere","2":"9"},"10":{"0":"image03.jpg","1":"texthere","2":"10"},"length":"12"};
function getArray(object){
var array = [];
for(var key in object){
var item = object[key];
array[parseInt(key)] = (typeof(item) == "object")?getArray(item):item;
}
return array;
}
var dataArray = getArray(dataObject);
I've got a PHP array and echo that into javascript with json encode, i need to do it this way because it's going to be very dynamic. This is the code it echo's:
{"notempty":true}
And i use this to, convert it to javascript:
var myarray = eval('(' + json + ')');
For some reason it creates an object instead of an array and for that reason i cant use .length or a for loop.
Does someone know what im doing wrong here?
Thanks
You're trying to treat an Object like an Array, and an Object is not an Array, it is an Object.
Any time you see {} in JSON, that means "What is contained within these hallowed brackets is a dynamic object". When you see [], that means "Behold! I am an Array" (there are notable exceptions to this one: jQuery does some special work with to make itself look like an array).
So, in order to iterate through an Object, you'll want to use for... in.
// eval BAD unless you know your input has been sanitized!.
var myObj = JSON.parse('{"notempty":true}');
// personally, I use it in for... in loops. It clarifies that this is a string
// you may want to use hasOwnProperty here as sometimes other "keys" are inserted
for( var it in myObj ) console.log( "myObj["+it+"] = " + myObj[it] );
{} is an object, which contains one attribute named notempty. If you want an array, it'd have to be
[{"notempty":true}]
which is an array with a single element at index 0, which is an object with the single attribute 'notempty';.
By default, if you use encode an assoc array in php, it will become a js object when you decode. In order to have it be an array, you need to make it an array in php:
PHP:
$arr = "['notempty','notempty2','notempty3']";
Otherwise, you should convert it to an array in JS, but that seems to me a waste since looping through the object in javascript is so much easier:
Javascript:
var arr = new Array();
for(var i in obj) arr[i] = obj[i];
You can use jQuery to parse it into an array like this:
var p = [];
$.each(jsonData, function (key, val) {
p.push([val.propertyOne, val.propertyTwo]);
});
I am presuming of course that you want to parse JSON, not an array or any other string.