How to parse a file with multiple JSON in PHP (Laravel)?

I have an input file that looks something like this:

{"name": "foo"}{"name": "bar"}

      

How do I disassemble this?

+3


source to share


2 answers


If you are sure that the individual JSON is valid, you can try to convert it to an array of JSON objects, for example:

$data = '{"name": "foo"}{"name": "bar"}';

$data = str_replace('}{', '},{', $data);
$data = '[' . $data . ']';

// Now it valid
// [{"name": "foo"},{"name": "bar"}]

      



Since it is }{

always invalid in JSON, it's safe to say it won't affect your data.

+3


source


there are several ways to parse json objects like this .. but you should know the exact structure of this object.

one way is to repeat each child element.



foreach($jsonObj as $obj)
{
    // access my name using
    $obj->name;
    $obj->someotherfield
    // or iterate again .. assuming each object has many more attribute
    foreach($obj as $key => $val)
    {
        //access my key using
        $key
        // access my value using
        $val
    }
}

      

there are many other ways to do it like this ... and also, valid json is like [{"name": "foo"},{"name": "bar"}]

0


source







All Articles