Skip to content

Instantly share code, notes, and snippets.

@cam-gists
Created September 8, 2012 05:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cam-gists/3672009 to your computer and use it in GitHub Desktop.
Save cam-gists/3672009 to your computer and use it in GitHub Desktop.
JavaScript / PHP: JSON Object to PHP Object
/**
* Converts a JS object to PHP object
**/
function jsObj2phpObj(object){
var json = '{';
for(property in object){
var value = object[property];
if(typeof(value) == 'string'){
json += '"' + property + '":"' + value + '",'
} else {
if(!value[0]){
json += '"' + property + '":' + jsObj2phpObj(value) + ',';
} else {
json += '"' + property + '":[';
for(prop in value) json += '"' +value[prop]+ '],';
json = json.subtr(0, json.length-1)+"],";
}
}
}
return json.subtr(0, json.length-1)+"}";
}
// Usage JS side
var json = jsObj2phpObj(object);
$.post(base_url + 'ajax/setup_user', {json: json}, function(data, textStatus, xhr) {
//optional stuff to do after success
console.log(data);
});
// Usage PHP side
function jsonString2Obj($str){
return json_decode(stripslashes($str));
}
@dugjohnson
Copy link

The json.substr is mis-typed above as subtr. Once that's fixed it works nicely.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment