Trim leading and trailing white spaces in JSON val

2019-08-15 00:34发布

问题:

All,

I make a JSON request to a web server using PHP and it returns me a JSON response in a variable. The JSON response will have lots of keys and values. I would like a function which trims leading and trailing white spaces in each "value" of the key-value pair for the entire JSON response.

How can I do that through PHP?

Ex: json_decode breaks due to trailing spaces or special characters:

{
    "glossary": {
        "title": "example glossary",
  "GlossDiv": {
            "title": "S",
   "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
     "SortAs": "SGML",
     "GlossTerm": "Standard Generalized Markup Language‡flfi·€..  ",
     "Acronym": "SGML",
     "Abbrev": "ISO 8879:1986",
     "GlossDef": {
                        "para": "create markup languages such as DocBook.     ",
      "GlossSeeAlso": ["GML", "XML"]
                    },
     "GlossSee": "markup"
                }
            }
        }
    }
}

回答1:

Process the data BEFORE it's encoded into JSON format. Better to clean up the source than mess with the JSON version and possibly break the syntax with a malformed regex deleting something it shouldn't have.

Basically, do this:

foreach($data as $key => $value) {
    $data[$key] = trim($value);
}

$json = json_encode($data);  // $json's values are now pre/post-whitespace free

(assuming it's a simple 1-dimensional array).

edit/comment followup:

Is your PHP script fetching this external JSON? If that's the case, then you can trivially decode the JSON into a PHP object/array, do the whitespace trimming, and re-encode into JSON:

$json = get_json_from_external_source();
$data = json_decode($json);

and then the foreach loop (or array_map as mentioned in Tomalak's comment) as before. If you're limited to doing this client-side in Javascript, then you can do the equivalent processing there before handing the data over to whatever function requires it.

edit/comment followup #2:

I highly doubt it's the trailing spaces inside the JSON data's values. JSON is perfectly capable of handling spaces wherever they occur within a string and doesn't care how many (or few) there are. Most likely it's the funky characters in the GlossTerm entry.

If you're on PHP 5.3 (or a higher beta version), there's json_last_error() which will report as to why the decode's failing.