Troubles encountered while parsing nested JSON objects with a streaming parser

I'm currently using the code provided in this helpful resource for parsing my JSON:

Although it successfully handles most of the JSON data I have, it encounters issues when a JSON object is directly nested as a child within another one.

To illustrate the problem, here's a simplified example of my JSON structure:

[
    {
        "title": "Title",
        "child_object": {
            "title": "Child Title"
        }
    },
    {
        "title": "Title 2",
        "child_object": {
            "title": "Child Title 2"
        }
    }

]

Once the parsing is completed, the resulting output becomes:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [title] => Title
                )

            [child_object] => Array
                (
                    [title] => Child Title 2
                )

            [2] => Array
                (
                    [title] => Title 2
                )

        )

)

If I transform the child object into an array, the parser will generate the desired output, which is identical to what I would obtain by using the json_decode function on the JSON data:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [title] => Title
                    [child_object] => Array
                        (
                            [0] => Array
                                (
                                    [child_title] => Child Title
                                )

                        )

                )

            [1] => Array
                (
                    [title] => Title 2
                    [child_object] => Array
                        (
                            [0] => Array
                                (
                                    [title] => Child Title 2
                                )

                        )

                )

        )

)

Does anyone have any suggestions on how to resolve this issue and properly place the child object during the parsing of the JSON file?

Answer №1

This code demonstrates the following functionality:

$text = '[
    {
        "title": "Title",
        "child_object": {
            "title": "Child Title"
        }
    },
    {
        "title": "Title 2",
        "child_object": {
            "title": "Child Title 2"
        }
    }

]';

$jsonData = json_decode($text);

foreach($jsonData as $item) {
    echo $item->{'title'};
    echo $item->{'child_object'}->{'title'};
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing JSON format into a DataTable using C#

Currently, I am attempting to transform a JSON string into a DataTable within WEBAPI The structure of the JSON string is as follows: [ [ "Test123", "TestHub", "TestVersion", "TestMKT", "TestCAP", ... ...

Tips for retrieving both the billing and shipping email addresses for all WooCommerce orders using a PHP array

add_filter( 'manage_edit-shop_order_columns', 'custom_shop_order_column',11); function custom_shop_order_column($columns) { $reordered_columns = array(); // Woocommerce version 3.3+ compatibility $location_after = version_compa ...

Problem with Array Serialization

I have a situation where I am serializing information using jQuery and storing it in a MySQL database: $(function () { $("#sortable").sortable({ stop: function (event, ui) { $("#q35list").val($(this).sortable('serialize') ...

Showing Json information using ajax in Codeigniter 4

Although I can see my JSON data in the browser console, I am unable to display it in the template. <script type="text/javascript"> $(document).ready(function () { $.ajax({ url: '<?php echo_uri("clients/session_ ...

Utilizing integer-based polymorphic deserialization instead of string-based approach in Jackson

Typically, when utilizing polymorphic deserialization with Jackson, I usually have a string field that corresponds to a particular class, and the implementation may look like this. @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo. ...

Is there a method available to minimize the size of a local storage list containing strings?

Hey there, I am trying to load a large 2.5MB json file in my browser so that I can use it for some typeAhead functions. Unfortunately, I'm facing an issue with my local storage being constantly full. When using Firefox, I receive the following error ...

What's the least amount of pagination we can get away with?

What is the simplest form of pagination in PHP/MySQLi? I have done some research online and attempted to learn how to implement pagination, but all the examples I found were quite complex. I am looking for the bare minimum requirements to get started and g ...

Include certain variables in the JSON response within the Aspect

Our goal is to include some variables in the JSON response, embedded within a specific aspect. We are looking to implement a process similar to this function, but focusing on modifying the response rather than the request. ...

Retrieve information from a PHP file using AJAX when the output is just a single line

I never thought I would find myself in this situation, but here I am, stuck. I just need a single result from this PHP file, so is using an array really necessary? Despite my efforts to console.log(result) multiple times, all I get back is "null". What c ...

Tips for retrieving and presenting information from a JSON document in a React TypeScript application

I am struggling to display data in a list format using TypeScript. I am able to fetch the data but unable to display it properly. I am currently using map to iterate through an array of JSON objects. //json file [ { "id": "6s", ...

Steps for sending an email with PHP

After running this code, a new tab opens and displays my code. How can I resolve this issue? <?php $mail = new PHPMailer(); //Sending mail via Gmail if($send_using_gmail){ $mail->IsSMTP(); // instructing the class to utilize SMTP $mail->S ...

What is the best way to return JSON from a 403 error using Express?

Express has the ability to handle errors, and you can send back JSON data when returning a 403 status code like this: let error = {errorCode:"1234"} res.sendStatus(403, {error: error}); To catch and inspect the error in your frontend JavaScript, you can ...

Innovative method for dynamically loading a JavaScript file? [completed]

Closed. This question requires additional details or clarity. It is not currently accepting answers. ...

Why does PHP_SELF fail when there is a $_get parameter in the URL?

Here's a scenario: My website's URL looks something like http://localhost/coursera/instructor/course.php?id=1&name=web%20development&section=overview On this particular page, there exists a form: <form action="<?php echo $_SERVER[ ...

After performing a URL rewrite, the Yii Ajax save operation returns a 301 response

I've implemented an inline editor that utilizes AJAX to save content by calling a Yii controller. The process works perfectly fine. However, after shortening my URLs using .htaccess and Yii urlManager, I encountered a 301 response when trying to save ...

Complete my search input by utilizing ajax

It's only been 30 minutes since my last post, but I feel like I'm making progress with my search posts input: I've developed a model that resembles this: function matchPosts($keyword) { $this->db->get('posts'); ...

Form a collection and calculate

Greetings from France, I hope my message finds you well! I recently spent a year in the USA, but now back in France... Let me share some code snippets with you. I have received this data from a form: cmdId[] 25 cmdId[] 26 cmdId[] 27 cmdId[] 28 cmdId[] 29 ...

Ajax request causing bootstrap success message to have shorter visibility

I encountered an issue with my ajax form that retrieves data using the PHP post method. Instead of utilizing the alert function in JavaScript, I decided to use a bootstrap success message. However, there is a problem as the message only appears for less th ...

Avoid multiple clients from re-evaluating Redis values simultaneously

Imagine a scenario where our website has important counters on every page, making it heavily loaded. These counters are stored in Redis keys that automatically expire in an hour. Within our code, we have a check to see if a key containing a counter exists ...

The AWS lambda function is failing to process the POST variables

Despite working correctly in the AWS Lambda dashboard, my lambda function seems to be ignoring any json data that is posted to it. When testing with curl: curl -X POST -H "Content-Type: application/json" -d '{ "email":"[email protected]", " ...