1

I have user entered JSON. This means I sometimes get tabs, newlines etc outside of quotes where they are making it pretty. Prior to processing I'd like to strip these unwanted characters.

For example (from log):

{#015#012#011#011#011#011"dest":"dest@email.com",#015#011#011#011#011"sender":"sender@email."}

In reality

{\r\n\t\t\t\t"dest":"dest@email.com",\r\n\t\t\t\t"sender":"sender@email."}

How can I strip these unwanted characters from outside the quotes, without affecting deliberate characters inside the quotes?

Paul
  • 578
  • 1
  • 8
  • 23

1 Answers1

1

You don't need to strip out "\t" or "\n" in this case. All you have to do is json_decode the string, and you will get the correct key/value pairs.

$json = "{\t \t\n \"dest\":\"dest@email.com\",\r\n \t\"sender\":\"sender@email.\"}";
foreach(json_decode($json,TRUE)as $key=>$value){
    echo "#$key:$value#\n";
} 

Output:

#dest:dest@email.com#
#sender:sender@email.#

As you can see, the "\t" and "\n" are not part of the key. More over, and in the general case, if those characters are part of the value, you may want to keep them intact (an example would be a multi-line uer address)

MegaAppBear
  • 1,220
  • 1
  • 9
  • 11
  • Awesome! I took your answer and adapted to: $json = json_encode(json_decode($json, TRUE)); This gives me exactly the same json back, but without the fluff. Thank you! – Paul Mar 01 '15 at 10:24