Reputation: 837
I am a PHP developer working on code that will step through and parse a JSON object so that I can manipulate data before outputting it in its final form. Here's some example JSON (its very large so I am removing most of the items I need and just putting the invalid part):
[
{
"items": [
{
// this is valid and what I need.
}
],
"espots": [
{
"content": "
[TopNavigation_Appliances]
"
}
]
},
I have effectively stripped the JSON from its source to be strictly the JSON data that's being passed to json_decode(). However, I am always getting a null result because the JSON object has an invalid part that my code doesn't actually require to function. The whole "espots" part of the JSON is unneeded within my application, but the multiple line "content" part is screwing json_decode(). Is there a way in PHP via RegEx or some nifty PHP that will strip out these items from the JSON output so that I can properly use json_decode() to retrieve n array that my code can then manipulate and deal with in the way I need it to?
Here is the error message given by JSONLint (and one other validator):
Parse error on line 263:
... "content": "[TopNavigation_App
-----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
I'm gathering that "[ is causing invalid JSON, but I'm no expert on Json.
I've attempted the following to no avail:
Upvotes: 0
Views: 4581
Reputation: 837
I solved this by using the following RegEx to strip out whitespace & then the offending "espots" from above:
preg_replace('#, "espots":.*?}\s]#', '', preg_replace('/\s+/', ' ',$nearlyThere[0]));
Then minor str_replaces on random invalid strings that weren't in the original post to get it 100% valid.
Upvotes: 0
Reputation: 2471
Is the JSON coming in as a String? Its not the "[" but the new line in front of the square bracket that's throwing things off. If so you probably can use str_replace like:
$jsonStr = str_replace("\n", '', str_replace("\r", '', $jsonStr) );
But then its difficult to know for sure without more code.
Upvotes: 2