JSONify Python to feed into PHP - php

========== EDIT: ==========
Based on the below question, and below answer to use JSON. I'm rephrasing the question.
How can I take data from boto dynamo and jsonify it?
Right now I have something like this:
adv = #my advertiser
ads = self.swfTable.scan(advertiser__eq = adv)
arr=[]
for a in ads:
arr.append(a)
str = []
for i in arr:
str += [json.dumps(fields) for fields in i]
if str is not []:
json.dumps([ str.to_json() for ad in str ])
How do I turn this into a nice JSON dump or otherwise send it to my php?
========== Original Question: ==========
Forgive me I'm new to PHP.
So I have a stringified array of objects.
Ex:
Array [{cat,bat},{mat,hat}] -> ["cat","bat","mat","hat"] (let's call this aList below)
If I know each object pair will have a length of two. Is the only way to reform this Array by parsing the string? Is there any clever PHP way to do this?
I'm trying to move data from python to PHP in this case and sending a printed array seemed like the best / most universal way for me to write the api connection.
Here is my solution in pseudocode:
aList = file_get_contents(myUrl)
splitList = aList.split(",") # is there anyway to exclude "," from being also noticed? ex "app,le","blueberry" should only split 1x?
objects=[]
newObject{}
for int i =0;i<splitList.len; i++
if i%2
newObject.append(splitList[i])
objects.append(newObject)
newObject = {}
else:
newObject.append{list[i]}
Is there are way to do this in fewer lines / more efficiently? Also as mentioned above: is there anyway to exclude "," from being also noticed? ex "app,le","blueberry" should only split 1x?

You really should consider cross-language serialization, like JSON or MessagePack. As an example, see docs for PHP's json_decode and Python's json.

Related

is it possible to receive only partial results in JSON from API calls using PHP?

I have been using PHP to call an API and retrieve a set of data in JSON.I need to make 20 batch calls at once. Therefore, speed is very important.
However, I only need the first element, in fact, I only need one data which is right at the beginning of the JSON file, index 0. However, the JSON file returns about 300 sets of data. I have to wait until all the data are ready before I can proceed.
I want to speed up my API calls by eliminating redundant datasets. Is it possible for me to receive the first set of the data only without having to wait until everything is ready and then go indexing the first element?
excuse my english...thank you in advance.
you could use fopen to get the bytes that are guaranteed to have what you need in it and then use regex to parse it. something like:
$max_bytes = 512;
$fp = fopen($url, "r") ;
$data = "" ;
if($fp) {
while(!preg_match('/"totalAmount"\:"(.*)"/U', $data, $match))
$data .= stream_get_contents($fp, $max_bytes) ;
fclose($fp);
if(count($match)){
$totalAmount = $match[1];
}
}
keep in mind that you cant use the string stored in $data as valid json. It will only be partial
no. json is not a "streamable" format. until you receive the whole string, it cannot be decoded into a native structure. if you KNOW what you need, then you could use string operations to retrieve the portion you need, but that's not reliable nor advisable. Similarly, php will not stream out the text as it's encoded.
e.g. consider a case where your data structure is a LOOOONG shallow array
$x = array(
0 => blah
1 => blah
...
999,999,998 => blah
999,999,999 => array( .... even more nested data here ...)
);
a streaming format would dribble this out as
['blah', 'blah' ............
you could assume that there's nothing but those 'blah' at the top level and output a ], to produce a complete json string:
['blah'.... , 'blah']
and send that, but then you continue encoding and reach that sub array... now you've suddenly got
['blah' ....., 'blah'][ ...sub array here ....]
and now it's no longer valid JSON.
So basically, json encoding is done in one (long) shot, and not in dibs and drabs, just because you simply cannot know what's coming "later" without parseing the whole structure first.
No. You need to fetch the whole set before parsing and sending the data you need back to the client machine.

string delimiter ajax call

So a PHP file returns a string ( to an ajax call ) like this :
$output = $sessID."###".$sessEmail."###".$sessFirstName."###".$sessLanguage."###".$sessRememberMe;
and in javascript i do :
if (reply.indexOf("###") >= 0) {
arrayReply = reply.split("###");
user.ID = arrayReply[0];
user.Email = arrayReply[1];
user.FirstName = arrayReply[2];
user.Language = arrayReply[3];
user.RememberMe = arrayReply[4];
}
a problem can arise when parts of reply contain the the delimiter i use "###". What can I do in such a situation? Making the delimiter more complex/rare is not a solution in my opinion.
PS: I did try JSON but it's WAY SLOWER server side.
FINAL EDIT:
server side JSON is slower, and the same for client side, however it's not going to be a bottleneck ( 430ms for 100.000 calls ) and plus there is no need as Jules said below to re-invent the wheel. There was one more solution: bin2hex() in php [which reduced the time from 430ms to 240] and then get back the string in javascript with a hex2string function, however not worth the effort. JSON it is. Thank you all!
If as you say encoding as JSON is slower than you could try the following,
$output = '"' . some_kind_of_escape_function($sessID).'","'.some_kind_of_escape_function($sessEmail).'","'.some_kind_of_escape_function($sessFirstName).'","'.some_kind_of_escape_function($sessLanguage).'","'.$sessRememberMe.'"';
and of course replace some_kind_of_escape_function with the appropriate php function (e.g. addslashes or mysql_real_escape_string) it has been a while since I've done PHP development so choose the one that best suits your needs
Then it's a simple case of splitting by the comma and removing the quotes
One option is to use JSON object instead.
For PHP (using json_encode):
$output = json_encode(array(
"sessid" => $sessID,
"sessEmail" => $sessEmail,
"sessFirstName" => $sessFirstName,
"sessLanguage" => $sessLanguage,
"sessRememberMe" => $sessRememberMe
));
For JS (using jQuery method):
$.getJSON("/path/to/script.php", function(reply) {
user.ID = reply.sessid;
user.Email = reply.sessEmail;
user.FirstName = reply.sessFirstName;
user.Language = reply.sessLanguage;
user.RememberMe = reply.sessRememberMe;
});
Otherwise, you can use any other delimiter that possibly won't be found in the fields (or you can replace it throughout the fields). One of the examples is to use symbol of newline (\n).
Why develop your own format if there is already one?
use Json:
$output = json_encode(array('sessionID'=>$sessID,'sessionEmail'=>sessEmail,'sessionFirstName'=>$sessFirstName,'sessLanguage'=>$sessLanguage,'sessRememberMe'=>$sessRememberMe));
And for the Javsascript Side see
http://www.javascriptkit.com/dhtmltutors/ajaxgetpost4.shtml
or if your using JQuery etc. your Framework is much likely to have some kind of inbuild functionality such as http://api.jquery.com/jQuery.getJSON/
However if you want to use your ###-Delimiter i'd suggest you reduce it to just "#", for the sake of simplicity and space. After that introduce what is called an escape charater such as "\" So in a prepass you'll parse your input and replace all occurences of # with #, vice versa in the output. You can then Split your String using a special Regex, which only splits by # and not by "#"
You can use json.
http://php.net/manual/en/function.json-encode.php
How to JSON decode array elements in JavaScript?

Show php print_r in Flash?

Trying to figure out a way to get ActionScript to print out a php object. In PHP, I can just do print_r, and I'm able to successfully get the object into Flash, but now can't figure out how to print out the object using ActionScript 3?
Well, when the request first comes over, there is always URLLoader.data, which is data in its raw form. If you're looking to get the data from a JSON-style object, there is for( var i:String in obj ). If you're looking for things more obscure than that, there is the ability to use describeType. My favorite example of the last one is in the JSONEncoder class.
From PHP, you can encode most objects to JSON using json_encode() (PHP5+). Using the AS3 JSON decoder from as3corelib you can then convert that encoded string into an oject that AS3 con read. After that you can iterate over the object as key/value pairs and output it however you wish.
I think I know what you mean, I had the same need, so I made this
http://www.actionscript.org/forums/showthread.php3?t=266979
scroll to the bottom, there is a description and an .AS file called trace_r that I wrote

jQuery DataTables: server-side example with php and xml, no database

Looking for a way to setup a server-side datatable using PHP to parse XML json?
Okay, I'm getting the data from wufoo and so I am also able to pull json. How can I get started with the following data?
{"Entries":[{"EntryId":"33","Field71":"","Field41":"John","Field42":"Smith","Field55":"","Field34":"2004","Field375":"Arts, Design, Entertainment, Sports and Media","Field378":"Select One","Field4":"Kayak Outfitter","Field3":"Kayak Tours, Inc","Field7":"123 Main Street","Field8":"","Field9":"New York","Field10":"New York","Field11":"54209","Field12":"United States","Field19":"(555)555-5555","Field23":"contact#email.com","Field46":"http:\/\/www.website.com","Field21":"","Field49":"","Field6":"May>September","Field65":"","Field69":"","Field25":"","Field37":"Its all about Self-Motivation.","Field30":"Yes","Field31":"Yes","Field172":"","Field39":"","DateCreated":"2009-01-30 05:46:02","CreatedBy":"public","DateUpdated":"2010-08-08 22:23:30","UpdatedBy":"User"}]}
As Charles suggests DataTables will currently only accept a JSON input with a specific format. The reason for this is that supporting abstract formats would add a lot of overhead to both the internals and the initialisation (i.e. you'd need to tell it that you want it to use //articles/book#author or whatever).
So one option is to use fnServerData ( http://datatables.net/usage/callbacks#fnServerData ) to make your own Ajax call and get the XML - than transform it into the JSON format that DataTables needs with a simple loop.
Allan
Thanks for the sample data.
You're going to need to convert the data slightly.
DataTables can take a Javascript data structure (JSON), but it has to be an array of arrays.
Your sample data has a root element called Entries, which contains an array. That's great. Unfortunately each element in that array is currently a hash -- a key/value pair.
You need only the values from that pair, not the keys.
This Javascript will convert your Entries array-of-hashes into a plain old array-of-arrays. I'm using the Javascript 1.6 for each ... in syntax here because I had a brainfart and didn't remember that we're talking about a jQuery plugin here, and wrote it without that dependency.
var entries = /* JSON as provided in question */;
var new_array = new Array();
var el = entries['Entries'].length;
for(i = 0; i < el; i++) {
var inner_array = new Array();
for each (var value in entries['Entries'][i]) {
inner_array[ inner_array.length ] = value;
}
new_array[ new_array.length ] = inner_array;
}
You can then pass new_array into the initial options hash's aaData option, as documented in the link I provided above. You will need to work out how to present the column headings yourself, given that you seem to have fallen into the anti-pattern of useless key names.

Turn Javascript String into PHP array

I'm not talking about JSON. I've got a program with the input being a javascript data structure in string format, something like this:
$string = "
var records = new Array();
records[0] = new Record('data1','data2',data3');
records[1] = new Record('data1','data2',data3');
records[2] = new Record('data1','data2',data3');";
Is there an easy way/library to turn this into a PHP data structure? The only way I can think of is to use str_replace to manipulate the string in order to turn it into JSON and then use json_decode.
Just wondering if there's a better way to do it.
Nope, you pretty much hit on the best way to do it.
You can post it to PHP as a string delimited by some character:
$phpArray = explode(",",$postValue);
This is not a better way just another way to do it. But not without potential problems. You have to ensure the delimiter you use is not used in the text and validate.

Categories