0

For reference I'm using EasyPost (shipping API) to make PHP calls checking shipping rates and what not. Their code is all about using it to echo data back to the page as a PHP object, but I'm trying to use jQuery ajax to get JSON data back from it to use in my ember.js app.

In talking with someone from EP (EasyPost) about why I could not get it to encode to JSON correctly for my app he told me that what is returned from EP is a PHP object, and that I would need to build an array before json_encode will work.

Below is the example response from their site...

{
  "id": "prcl_WDv2VzHp",
  "object": "Parcel",
  "length": 20.2,
  "width": 10.9,
  "height": 5.0,
  "predefined_package": null,
  "weight": 65.9,
  "created_at": "2013-04-22T05:40:57Z",
  "updated_at": "2013-04-22T05:40:57Z"
}

I'm not versed enough in PHP to understand how I would go about building an array from this to then be able to json_encode it.

It should also be noted that some responses have points that look like this...

"from_address": {
"id": "adr_VgoLT6Ex",
"object": "Address",
"name": "Jon Calhoun",
"company": null,
"street1": "388 Townsend St",
"street2": "Apt 20",
"city": "San Francisco",
"state": "CA",
"zip": "94107",
"country": "US",
"phone": "4154567890",
"email": null,
"created_at": "2013-04-22T05:39:57Z",
"updated_at": "2013-04-22T05:39:57Z"
},

and ...

"rates": [{
  "id": "rate_nyCb6ubX",
  "object": "Rate",
  "service": "FirstClassPackageInternationalService",
  "rate": "9.50",
  "carrier": "USPS",
  "shipment_id": "shp_vN9h7XLn",
  "created_at": "2013-04-22T05:40:57Z",
  "updated_at": "2013-04-22T05:40:57Z"
},...

Hoping someone can point me in the right direction, if I understand how to get each bit out and make it an index in the array I think I can go from there. As I really don't need some of the data that is returned anyway.

KFunk
  • 2,956
  • 22
  • 33
Jordan
  • 2,393
  • 4
  • 30
  • 60
  • Have you looked at json_decode? http://us1.php.net/json_decode Here is the post on SO http://stackoverflow.com/questions/5164404/json-decode-to-array – Jay Blanchard Mar 12 '14 at 18:05
  • `$array=json_decode($json, true);` will give you an array – CodeBird Mar 12 '14 at 18:06
  • json_decode worked, I thought for some reason that was only when you were trying to take json and turn it into an array or object and not the other way around. – Jordan Mar 12 '14 at 18:08
  • Er... What you've posted _is_ JSON. Why can't you send that straight to your client and parse it in JS? – Bojangles Mar 12 '14 at 18:09
  • I tried but it was sending all empty objects for some reason – Jordan Mar 12 '14 at 20:02

1 Answers1

1

You could use JQuery serialize()

obj.serialize();

and post it to php file in your server

In that php file use json_decode

$arr = json_decode($_POST['receivedData'],true);
dlock
  • 9,447
  • 9
  • 47
  • 67
vimal1083
  • 8,499
  • 6
  • 34
  • 50