Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, Invalid characters in JSON decode

Tags:

json

php

I'm having troubles getting json_decode to work on a specific string I am receiving.

I have narrowed it down to this line:

"systemNotes[6]": "January 09, 2013 12:52 PM - Test Name - Changed Billing Address 2 From to Shipping First Name: Shipping Last Name: Email Address: Shipping Address: Shipping Address 2: Shipping City: Shipping Zip/Postal: Shipping Country: Shipping State: Phone: Billing First Name: Billing Last Name: Billing Address: Billing Address 2: Billing C"

Copying the json from this question, the problem is not reproducible - but a representative snippet of the original json is here: http://codepad.org/ZzrC7rqQ - and putting that in jsonlint.com gives:

Parse error on line 3:
...  "systemNotes[6]": "January 09, 2013 12
-----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

What is wrong with this string such that it's invalid json?

EDIT

I managed to find the exact code coming across.

"systemNotes[6]":"January+09%2C+2013+12%3A52+PM+-+First+Name+-+Changed++Billing+Address+2+From++to+Shipping+First+Name%3A%09+Shipping+Last+Name%3A%09+Email+Address%3A%09+Shipping+Address%3A+%09+Shipping+Address+2%3A+%09+Shipping+City%3A+%09+Shipping+Zip%2FPostal%3A+%09+Shipping+Country%3A+%09+Shipping+State%3A+%09+Phone%3A+%09+Billing+First+Name%3A+%09+Billing+Last+Name%3A+%09+Billing+Address%3A+%09+Billing+Address+2%3A+%09+Billing+C"

This seems to be ok so maybe the problem is coming from when I do the parse_str, here's the code I am using:

$response = apiConnection($data);
parse_str($response, $parse);
$each = json_decode($parse['data']);
foreach($each as $key => $order){
   //do something
}
like image 263
Scott Avatar asked Jul 19 '13 18:07

Scott


2 Answers

The problem is that tab characters are not valid inside a string.

Removing the tab characters like here http://codepad.org/8fnQphkS and using that at jsonlint.com you will see it see now valid json.

Have a look at the specs for JSON at http://www.ietf.org/rfc/rfc4627.txt?number=4627 specially section 2.5 where the tab character is called out by name as one of the characters that must be escaped if inside a string.

EDIT:

Here is a way of stripping out all tabs and multiple spaces and replacing them with a single space character:

$data = preg_replace('/[ ]{2,}|[\t]/', ' ', trim($data));
like image 198
CodeReaper Avatar answered Oct 20 '22 17:10

CodeReaper


did you try something like that? it would help to clean your string

$yourstring = preg_replace('/[^(\x20-\x7F)]*/','', $yourstring);
like image 6
Pascamel Avatar answered Oct 20 '22 16:10

Pascamel