Pass string to json with jquery and loop the elements - php

Hello there I have a really complex php script that produces a javascript file in jquery
There is a string that is stored in an input type text and I want to converted into json.
The input type text has undedined number of elements.
So I initisialize the string in the input box
<input type="text" id="selectbuttons" value="{}">
After some actions the string in the input box is something like that:
{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}
etc...
Then this is my script , i use the function addScriptto to add it to the document's header, also I am using the core of jquery jquery-1.6.2.min.js to make the json object
$document->addScriptto('
$.noConflict();
jQuery(document).ready(function($) {
var loaded=$("#selectButtons").val();
var obj = jQuery.parseJSON(loaded);
}); //end of dom ready
');
But I can't make it work, when the string is not empty
Is there something wrong with my json syntax? Also, I would be later able to loop all the elements and retrieve the data? Thanks in advance

Your JSON string should be in an array format like below
[{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}]
And then you can use the $.each to loop through the JOSN values as below:
$.each(yourJSONstring,function(i,values) {
//yourJSONstring holds the JSON array
// i is just the loop index. it will increment by 1 in every loop
alert(values.button) //will alert bt1 in the 1st loop, bt2 in 2nd
alert(values.style) //will alert style1 in 1st loop, style2 in 2nd
//You can have values here of the keys in JSON using the dot notation as above and do your operations.
})

maybe just put [ ... ] around the JSON so it is understood as an array, something like:
var obj = jQuery.parseJSON( '[' + loaded + ']' );

Yes, your JSON syntax is wrong. You should have it like:
[{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}]
and then you will have array of your objects.

Related

reformatting data received from api callback string

I am receiving from a php/curl callback to an api and using jquery if statements to output certain data.
For one particular call back string the data is returned like so:
response.endpoints[0].details.cert.subject
The value of the above string is:
CN=www.thawte.com,OU=Infrastructure Operations,2.5.4.5=#130733383938323631,2.5.4.15=#131450726976617465204f7267616e697a6174696f6e,L=Mountain View,ST=California,C=US,O=Thawte, Inc.,1.3.6.1.4.1.311.60.2.1.2=#0c0844656c6177617265,1.3.6.1.4.1.311.60.2.1.3=#13025553
What I would like to be able to achieve is extract certain parts of this string instead of displaying the entire value.
The following are fixed values which will always appear but I dont want the rest of the stuff..
How can I seperately extract the following bits:
CN=value
OU=value
L=value
ST=value
C=value
For example, in my output I want to set a variable to end up with "www.thawte.com" and a seperate variable for the each of the above.
You need to use foreach inside another foreach like this:
$(function(){
var valData= "CN=www.thawte.com,OU=Infrastructure Operations,2.5.4.5=#130733383938323631,2.5.4.15=#131450726976617465204f7267616e697a6174696f6e,L=Mountain View,ST=California,C=US,O=Thawte, Inc.,1.3.6.1.4.1.311.60.2.1.2=#0c0844656c6177617265,1.3.6.1.4.1.311.60.2.1.3=#13025553";
var valNew=valData.split(/,(?=\S)/);
var valArray_unprep = [];
var valArray_prep = [];
for(var i=0;i<valNew.length;i++){
var valArray_unprep = valNew[i].split('=');
for(var ii=0;ii<valArray_unprep.length;ii++)
valArray_prep[valArray_unprep[0]] = valArray_unprep[1];
}
console.log(valArray_prep);
alert(valArray_prep['CN']);
alert(valArray_prep['L']);
});

js json.stringify to PHP json_decode

I am new to JSON.
In JS, I create an array of values like so:
var arrFields = $("td>.frmInput").map(function(){
return {
id: this.id,
value: $(this).val()
};
}).get();
I then AJAX them to the server like so:
$.ajax({
type: "POST",
url: "ajax/ax_all_ajax_fns.php",
data: "Fields=" +JSON.stringify(arrFields),
success: function(recd) {
alert(recd);
}
});
Note that there is a mixture of strings, plus the JSON.stringified (?) array. (There are additional string values sent, so data must remain as string.)
On the PHP side, I need to turn the received Fields string into an associative array.
Doing this:
$jsonAsStr_Fields = $_POST['Fields'];
die($jsonAsStr_Fields);
Returns this text string in the alert():
[{"id":"rateDriver","value":"Jacques Villeneuve"},{"id":"rateCar","value":"Chev"}]
Doing this:
$arrFields = json_decode($jsonAsStr_Fields, TRUE);
$driver = $arrFields['rateDriver'];
$car = $arrFields['rateCar'];
$tire = $arrFields['rateTire'];
die('Driver: [' .$driver. '] Car: [' .$car. '] Tire: [' .$tire. ']');
Returns this:
Driver: [ ] Car: [ ] Tire: [ ]
How can I turn the $jsonAsStr_Fields string into an assoc array, and thereby output the correct values to my alert?
Do this instead for your creation of values:
var arrFields = {};
$("td>.frmInput").each(function(){
arrFields[this.id] = $(this).val();
});
This will create an object, when JSON-stringified, that looks like this:
{"rateDriver":"Jacques Villeneuve", "rateCar":"Chev"}
Which seems to be the format you want to use in your PHP code.
You have an array of associative arrays and your arrays don't have the specified props, rateDriver for example is the value of the first array's element's id:
$driver = $arrFields[0]['id'];
$car = $arrFields[1]['id'];
For seeing the array's contents you use the famous var_dump function.
From the Author:
For those who haven't fully understood what solved this problem.
The underlying problem was that the stringified JSON was being modified en route (immed after hit Submit button en route to the PHP side) by the AJAX. All quote marks were being escaped, which made it impossible for that string to work with json_encode.
This was discovered by grabbing the value of the received data once it hit the PHP side:
$jsonAsStr_Fields = $_POST['Fields'];
die($jsonAsStr_Fields);
And alerting the received data in the AJAX success function:
success: function(recd) {
alert(recd);
}
Both of the above were described in the OP.
However, because I assumed this was an unrelated problem, I "fixed" the string displayed in the alert() box when I posted the question. Lesson to be learned: don't help - just post what you actually see.
It really displayed like this:
{\"id\":\"rateDriver\",\"value\":\"Jacques Villeneuve\"}
but I wrote that it displayed like this:
{"id":"rateDriver","value":"Jacques Villeneuve"}
Of course, the json_decode() PHP function had no idea what to do with the backslashes, so the string did not convert.
Solution was to use str_replace() on the received JSON string over on the PHP side, to resolve the problem, like this:
str_replace("\\", "", $_POST['Fields']);

merge values of unique keys of json string

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

Assigning identifier/name to JSON object in PHP

I'm grabbing data from a mysql database and encoding a JSON object with PHP to use in JS.
On the PHP end, I did this
while($row = mysql_fetch_array($result))
{
$jmarkers = array(
'id'=> $row['id'],
'lat' => $row['lat'],
'lng' => $row['lng'],
etc...
);
array_push($json, $jmarkers);
}
$jsonstring = json_encode($json);
echo $jsonstring;
I can access the data in JS using jQuery, and I made an array to save the JSON data:
$.getJSON("getjson.php", function(data)
{
myMarkers = data;
console.log(myMarkers);
});
I'd planned to access the data in the myMarkers array inside loop, with a statement like this:
var tempLat = myMarkers.jmarkers[i].lat;
The problem is my JSON objects aren't called jmarkers or anything else, they have this generic name "Object" when I print them to the console:
Object { id="2", lat="40.6512", lng="-73.9691", more...},
So I'm not sure how to point to them in my JS array. I looked the PHP JSON encode function and I can't see where to set or change the object name. Any suggestions? Thank you!
That's to be expected. JSON is essentially the right-hand-side of an assignment operation:
var x = {'foo':'bar'};
^^^^^^^^^^^^^---- JSON
The x part is not included, since that's simply the name of the object. If you want your jmarkers text included, it'll have to be part of the data structure you're going to encode:
$arr = array(
'jmarkers' => array(...your data here...);
);
But all this does is add another layer to your data structure for no useful reason.
$jmarkers is simply the identifier on the PHP side for the JSON object. When it gets passed, it converts the array value into a JSON-encoded string and therefore loses the identifier as a result.
In your PHP code at the moment, array_push($json, $jmarkers) is appending an array to your current $json array. You are therefore instancing a two-dimensional array, which will not be retrievable by the jmarkers identifier in your Javascript code. Simply retrieve the data using myMarkers[i] instead.
You... don't. The whole thing is an object. You only need to refer to the elements within.
alert(myMarkers.id);

Parsing a JSON string to array, not object

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.

Categories