reformatting data received from api callback string - php

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']);
});

Related

JQuery returning string not array, despite apparent logic of code...why?

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.

Convert JSON to multidimensional JavaScript array

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);

foreach for javascript, json array

I have a JSON array that looks like this:
[{"RegDate":"31-03-2011"},{"RegDate":"29-07-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"12-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"23-08-2011"},{"RegDate":"07-09-2011"},{"RegDate":"09-09-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"03-11-2011"},{"RegDate":"03-11-2011"},{"RegDate":"11-11-2011"},{"RegDate":"16-11-2011"},{"RegDate":"18-11-2011"},{"RegDate":"21-11-2011"},{"RegDate":"02-12-2011"},{"RegDate":"02-12-2011"},{"RegDate":"12-12-2011"}]
The code to get this json array is as of the following:
var unavailableDates1 = jQuery.parseJSON('<?php echo json_encode($noticesDates) ?>');
I am trying too get all of the dates in that array (which was originally a multidimensional array), and put it inside one array:
var unavailableDates = ["9-3-2012", "14-3-2012", "15-3-2012"]; for example
I am unsure of how to do this, I have tried a foreach but wasn't successful.
All help will be appreciated.
First of all, that parseJSON is unnecessary and actually dangerous. Take it out:
var unavailableDates1 = <?php echo json_encode($noticesDates) ?>;
Then, just use jQuery.map:
var unavailableDates = $.map(unavailableDates1, function(item) {
return item.RegDate;
});
Using a string like that is dangerous for the following three objects, for example:
{"key":"Backslash here: \\"}
{"key":"I'm a horse!"}
{"key":"Some\\backslash"}
They become, respectively:
SyntaxError: Unexpected end of input (Single escape escapes end of string)
SyntaxError: Unexpected identifier (Unescaped single quote breaks out of the string, actually an XSS vulnerability)
Object
key: "Someackslash" (\\b becomes the \b backspace control character)
__proto__: Object
You could escape it again, but there's no need; valid JSON is always a valid JavaScript object, and you can trust your own PHP not to include injection code in there.
var justDates = [];
for (var i=0; i < unavailableDates1.length; i++) {
justDates.push(unavailableDates1[i]['RegDate']);
}
Each Object ({'RegDate:'date'}) is an item in a javascript array. To get an item you use a numerical index. so to get the first item would be theArray[0] this would give you {"RegDate":"31-03-2011"}. Then to get that particular date string you just have to use the key theArray[0]['RegDate']!. So since you want to go through every member of a list, you should get the list length using .length.
For loops are usually used for this type of iteration and not for..in. because for in can access properties that are undesired! http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/
have a look at how to iterate over an array.
You can do something like:
dates = new Array();
unavailableDates1.forEach(function (obj){
dates.push(obj.RegDate);
};
Try the following:
JavaScript:
var x = [{"RegDate":"31-03-2011"},{"RegDate":"29-07-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"12-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"23-08-2011"},{"RegDate":"07-09-2011"},{"RegDate":"09-09-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"03-11-2011"},{"RegDate":"03-11-2011"},{"RegDate":"11-11-2011"},{"RegDate":"16-11-2011"},{"RegDate":"18-11-2011"},{"RegDate":"21-11-2011"},{"RegDate":"02-12-2011"},{"RegDate":"02-12-2011"},{"RegDate":"12-12-2011"}];
var ary = new Array();
for (foo in x) {
ary.push(x[foo].RegDate);
}
console.log(ary);
jsFiddle example.
I noticed you tag jquery in here as well so, here's a jquery solution:
http://jsfiddle.net/aztechy/DK9KM/
var foo = [
{"RegDate":"31-03-2011"},
{"RegDate":"29-07-2011"},
{"RegDate":"09-08-2011"},
{"RegDate":"09-08-2011"}
];
var datesArray = [];
$.each(foo, function() {
datesArray.push(this.RegDate);
});
console.log(datesArray);​
Try This, it may works.
var unavailableDates = [];
for(var i = 0; i < unavailableDates1.length; i++){
unavailableDates[i] = unavailableDates1[i].RegDate;
}
for(var i=0;i<unavailableDates.length;i++) {
unavailableDates[i] = unavailableDates[i].RegDate;
}

Pass string to json with jquery and loop the elements

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.

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