Php preg_split and replace

This code is currently working. It breaks the $ json variable where it is}, {but it also removes these characters, but I really need the trailing and leading brackets for the json_decode function to work. I created a job, but wondered if there is a more elegant solution?

<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5},{"a":1,"b":2,"c":3,"d":4,"e":5}'; $individuals = preg_split('/},{/',$json); $loop_count =1; foreach($individuals as $object){ if($loop_count == 1){$object .='}';} else{$object ="{".$object;} print_r(json_decode($object)); echo '<br />'; $loop_count++; } ?> 

EDIT: The $ json variable is actually retrieved as a json object. The correct example is:

[{"ID": "Foo", "row": 1, "column": 1, "height": 4, "width": 5}, {"identifier": "bar", "row": 2, "column": 3, "height": 4, "width": 5}]

+4
source share
2 answers

As you (presumably) already know, the line you should start with is not valid json due to the comma and two objects; these are basically two json lines with a comma in between.

You are trying to solve this problem by separating them, but there is a much simpler way to fix this:

A workaround is to simply turn the string into valid JSON by enclosing it in square brackets:

 $json = '[' . $json . ']'; 

Voila. The string is now valid json and will be successfully parsed with a single json_decode() call.

Hope this helps.

+4
source

You can always add them again. Try the following:

 $json = '{"a":1,"b":2,"c":3,"d":4,"e":5},{"a":1,"b":2,"c":3,"d":4,"e":5}'; $individuals = preg_split('/},{/',$json); foreach($individuals as $key=>$val) $individuals[$key] = '{'.$val.'}'; 
0
source

Source: https://habr.com/ru/post/1481471/


All Articles