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.
Related
I have the following angularjs code for posting value to php:
$scope.aToUn = function(aName) {
//$scope.question.question_16 =UnionsId;
var outputType=[{type:'aName',action:'none',PassId:aName}];
$http.post('addressManagement.php',outputType).success(function(dataJsonUnions) {
//alert(dataJsonUnions);
$scope.question =dataJsonUnions;
//question or dataJsonUnions is an object that passed from json,
//something like question={{id="2",questionvalue="Name"}}
//calling another function
$scope.anotherFunction(questionvalue); // here i want to pass only value that from json eg. 'Name' only)
});
};
I am getting json object value, which i want to do something with that only single value. (object contain only one single value, dont want if/else or foreach)
Did you try
$scope.anotherFunction($scope.question[0].questionvalue);
As i understand your question, You first need to conver json response to object by using angular.fromJson() and then pass object's property for example:
$scope.question = angular.fromJson(dataJsonUnions);
then call function with argument that you want to pass:
$scope.anotherFunction($scope.question.questionvalue);
hope this helps you.
If the response is a JSON object and if you want to access the value of field 'questionValue' then you can try the below.
var json = JSON.parse(dataJsonUnions);
json.questionValue; // THis will fetch you the value
//OR
json['questionValue'];
// Then you can pass this value to any function that you need
I have a php array that I assigned to a javascript variable with json_encode. The php array is numerical not associative.
Example: simpleArray[5][7]=1.50. I need to be able to access the 1.50 after the array has been json_encoded based on the index values.
PHP:
$simpleArray= [];
foreach($childProducts as $child) { //cycle through simple products to find applicable
$simpleArray[$child->getVendor()][$child->getColor()] = $child->getPrice();
var_dump ($simpleArray);
}
Javascript:
var simpleArray = <?=json_encode($simpleArray)?>;
//..lots of unrelated code
for(var i=0; i < IDs.length; i++)
{
console.log(simpleArray);//see the picture of me below
var colorSelected = $j("#attribute92 option:selected").val(); //integer value
$j('.details'+data[i].vendor_id).append('<li class="priceBlock">$'+simpleArray[i][colorSelected]+'</li>');
}
Console.log(simpleArray):
Here you are likely trying to access values that don't exist in your object:
simpleArray[i][colorSelected]
Based on your for loop definition, you can have i values of 0, 1, 2 which don't exist in the object shown (which has properties at keys: 3,4,5). Also your for loop has no relation at all to the number of items in your object, which I am not sure is intended.
Also, colorSelected derives it's value from a call to val() which returns a string you you probably want to change the line where it is defined to:
var colorSelected = parseInt($j("#attribute92 option:selected").val());
This will make it an integer 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 have a json output code like this:
{"a":{"p1":"1"},"a":{"p2":"2"},"b":{"b1":"b2"}}
how to convert it to below using javascript or jquery or php ?
{"a":{"p1":"1","p2":"2"},"b":{"b1":"b2"}}
EDIT:
i generate json code by this code:
parts2.push('"'+$(this).attr('alt')+'":{"'+$(this).attr('title') + '"' + ":" + '"'+$(this).attr('value') + '"}' );
however $(this).attr('alt') maybe repeated in loop and i want to prevent duplicate key and instead append value to that key
Each property of an object is supposed to have a unique key name. If you try to parse JSON with duplicate key names, only the last occurring value is used, so it isn't possible to parse this with the native JSON.parse and still expect data to be preserved.
As per your edit, you can prevent the duplicates from ever occurring:
var obj = {};
if typeof obj[$(this).attr('alt')] == "undefined"
obj[$(this).attr('alt')] = {};
obj[$(this).attr('alt')][$(this).attr('title')] = $(this).attr('value');
parts2.push(JSON.stringify(obj));
You should merge the value before you generate the JSON string or you have to implement a JSON parser yourself to parse your JSON.
In http://www.ietf.org/rfc/rfc4627.txt?number=4627:
The names within an object SHOULD be unique
Instead of stringing the pseudo-JSON, just create an object, fill that, and stringify the object when you send it:
var parts = {};
$('.foo')each(function()
{//the loop, here parts is being filled
parts.[$(this).attr('alt')] = parts.[$(this).attr('alt')] || {};//initialize to object if property doesn't exist
parts.[$(this).attr('alt')] = [$(this).attr('title')] = $(this).attr('value');
});
//make JSON:
partsJSON = JSON.stringify(parts);
//{a:{p1:foo,p2:bar},b:{p3:foobar}} or something
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.