Removing extra characters from a string with a specific pattern PHP
<p>I am moving data from the output of a python function to php and then converting it to JSON and sending it to a javascript function that calls it with AJAX. </p>

<p>The format should look like this:</p>

<pre><code>{"data_name" : [1.02, 3.013, -24.12, 39], "data_name_2" : [-0.32151], "data_name_3" : [0.321, -21.42425, 225125.002]}
</code></pre>

<p>Right now, python is returning the data via <code>json.dumps</code> and the output is kind of strange once it reaches PHP. Since the data is already json from Python, <code>json_encode</code> does not work properly, but just echoing the json data produces this:</p>

<pre><code>"[{\"data_name\" : [[1.02], [3.013], [-24.12], [39]]}, {\"data_name_2\" : -0.32151}, {\"data_name_3\" : [[0.321], [-21.42425], [225125.002]]}, null]"
</code></pre>

<p>So how can I do the following things?</p>

<ol>
<li>Remove the first <code>"[</code> from the beginning of the string</li>
<li>Remove all the backslashes before the quotes (so <code>\"data_name\"</code> becomes <code>"data_name"</code>)</li>
<li>Remove <code>}, {</code> from each of the fields (except the first one)</li>
<li>For the 2D arrays, remove the inner <code>[]</code> symbols, so that <code>[[1.02], [2.02]]</code> becomes <code>[1.02, 2.02]</code></li>
<li>For the single numbers, add a <code>[]</code> around them, so <code>-0.32151</code> becomes <code>[-0.32151]</code></li>
<li>Finally, once I reach <code>}, null]"</code>, I want to remove <code>, null]"</code> and just keep the end <code>}</code>.</li>
</ol>

<p>I understand a little about <code>strpos</code> but I'm not sure how I can incorporate that with some form of regex, or if I need to manually loop through the string to take care of each of the steps. If anyone has an idea of how to start I would appreciate it.</p>

<p>I agree with Sammitch. </p>

<p>The quick fix for 2. is <a href="http://php.net/manual/en/function.stripslashes.php" rel="nofollow">stripslashes</a></p>

<p>For the rest, you may be able to create patterns with <a href="http://php.net/manual/en/function.preg-replace.php" rel="nofollow">preg_replace</a> that can filter it correctly, but why not just change the python output?</p>

javascript php python json