C
C
cspdarixuz2020-11-09 04:08:29
PHP
cspdarixuz, 2020-11-09 04:08:29

How to parse json following each other with nesting?

They gave a stupid api method - it returns json objects one after another without a separator. I'm trying to figure out the most efficient way to sort it all out.

{"param1": "value1","param1": "value1","param1": "value1","param1": {},"param1": "value1"}{"param1": "value1","param1": "value1","param1": "value1","param1": {},"param1": "value1"}{"param1": "value1","param1": "value1","param1": "value1","param1": {},"param1": "value1"}

Those. follow each other in a row
{"key":"value"}
and in such an object may occur
"key":{"param2":"value2"}


I need to deserialize each into an object naturally.
nesting can be any in theory for such a task.
you need something in the spirit of "since we already met one opening {, it means that if one is found, we ignore it and look for it further }. If we find }, then we check that there is an equal number of { and } between the first { and }."?

I tried everything from Google regulars, they break down on nesting, but there’s still not enough brains to write my own, and why, I’m sure, someone has already done it.
(?<=\{\{).*(?=\}\})
breaks down
{([^}]*)}
breaks ,
etc.
Or ready to listen to methods easier and better! I can't see the obvious

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
Gip, 2020-11-09
@cspdarixuz

$str = '{"param1": "value1","param1": "value1","param1": "value1","param1": {},"param1": "value1"}{"param1": "value1","param1": "value1","param1": "value1","param1": {},"param1": "value1"}{"param1": "value1","param1": "value1","param1": "value1","param1": {},"param1": "value1"}';
$arr = explode('}{', $str);
print_r($arr);

Array
(
[0] => {"param1": "value1","param1": "value1","param1": "value1","param1": {},"param1": "value1"
[1] => "param1": "value1","param1": "value1","param1": "value1","param1": {},"param1": "value1"
[2] => "param1": "value1","param1": "value1","param1": "value1","param1": {},"param1": "value1"}
)

+ slightly file each element of the array with a file to a normal json string and then, as usual
, a perversion, of course

A
Artem Zolin, 2020-11-09
@artzolin

You can use json_decode()to convert to an array, rebuild and return to json back using json_encode()
Your example does not work, because you copied three arrays into one line. The one that works will return you one key => value

$json = '{"param1": "value1","param1": "value1","param1": "value1","param1": {},"param1": "value1"}';
$json = json_decode( $json, true );
var_dump($json); // печатает array(1) { ["param1"]=> string(6) "value1" }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question