Jump to content
iwato

Selecting a Value of JSON Object with Javascript

Recommended Posts

DILEMMA:  I have a fairly complex JSON object that is introduced via an AJAX call.  Unfortunately, my control panel tells me that it is undefined. Is this because it has no value?  Or, is it because I do not know how to read the value properly?

{"lastVisits"[{"firstVisit":{"prettyDate":"Monday, May 14, 2018"}}]}

The name of the variable into which it is read is visitor_data.  Am I reading the value of correctly?

visitor_data.lastVisits[0].firstVisit.prettyDate

Roddy

Share this post


Link to post
Share on other sites

My first guess would be that what you have is just a string instead of a JSON object. Log the full object into the console to see what it contains.

  • Like 1

Share this post


Link to post
Share on other sites

LastVisits within JSON object is not defined correctly

visitor_data = {"lastVisits": [{"firstVisit": {"prettyDate": "Monday, May 14, 2018"}}]};

visitor_data.lastVisits[0].firstVisit.prettyDate;

 

  • Thanks 1

Share this post


Link to post
Share on other sites

OK. I have fixed the problem.  I am now able to get prettyDate to appear.  Clearly I misunderstood the structure of the object read by the $.ajax( ) success function.  My having misinterpreted the structure of this object was no casual error, however.  For, the object consists of nearly 2000 lines of comma separated property-value pairs, nested array-like structures, and the like.  As a result, I am of the firm conviction that similar errors will occur in the future until I learn how to traverse and display the content of the object that I am dealing with.  Visual inspection, something that I can now do, is not enough, as I have no means of collapsing the various sub-elements of the object.  This said, surely there is a formal methodology for parsing the structure of a complex, many layered JSON object with Javascript.  Can this be achieved through a single, highly flexible, recursive function?  Or, must it be achieved one layer at a time through painstaking trial and error?  Still this latter would be better than what I am doing now.  Could someone, please, point me to a tutorial about how to parse and display such an object.

Roddy

Share this post


Link to post
Share on other sites

Its just a matter identifying object, transverse down to parent item, object/array using dot.notation and looping through each child item to display its value.

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0">
        <title>Document Title</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
        <script>
            visitor_data = {
                "lastVisits": [
                    {
                        "firstVisit":
                                {
                                    "prettyDate": "Monday, May 14, 2018",
                                    "otherItem": "recent"
                                }
                    },
                    {
                        "firstVisit":
                                {
                                    "prettyDate": "Monday, May 14, 2020",
                                    "otherItem": "in future"
                                }
                    },
                    {
                        "firstVisit":
                                {
                                    "prettyDate": "Monday, July 04, 1900",
                                    "otherItem": "WAY Way in the past"
                                }
                    }

                ]
            };

            $(function() {

                for (x in visitor_data.lastVisits) {
                    var para = document.createElement("p");

                    var paraText = document.createTextNode(visitor_data.lastVisits[x].firstVisit.prettyDate + " : " + visitor_data.lastVisits[x].firstVisit.otherItem);
                    para.appendChild(paraText);
                    document.body.appendChild(para);
}
});
        </script>
    </head>
    <body>

    </body>
</html>

 

Edited by dsonesuk
  • Haha 1

Share this post


Link to post
Share on other sites

For, the object consists of nearly 2000 lines of comma separated property-value pairs, nested array-like structures, and the like.

The computer doesn't care how many items are there, the only thing that matters is whether it follows the correct format.

Visual inspection, something that I can now do, is not enough, as I have no means of collapsing the various sub-elements of the object.

There are all kinds of text editors that will let you collapse whatever part of the structure you want.  The built-in developer tools in the browser will do that also if you print the structure to the console.

This said, surely there is a formal methodology for parsing the structure of a complex, many layered JSON object with Javascript.

There sure is, and the browser does all of that automatically.  I have never written code to parse a JSON structure, there's no reason to write that when it's a format the browser understands natively.  JSON is native Javascript, it stands for Javascript Object Notation.  The browser already understands it, you don't have to parse anything like that yourself.

Can this be achieved through a single, highly flexible, recursive function?

Yep.

Could someone, please, point me to a tutorial about how to parse and display such an object.

var obj = JSON.parse(json_str);
	console.log(obj);

  • Thanks 1

Share this post


Link to post
Share on other sites

Most browsers will show a collapsible representation of a data structure of you log it using console.log(). 

  • Thanks 1

Share this post


Link to post
Share on other sites

It took some time to find it, but I was finally able.  Unfortunately, I was unable to find anything in Chrome, and I have long since given up on Safari, as it is next to useless in my current operating environment.

The following is the procedure used to display the structure and contents of a result object that is generated in a PHP file called with an AJAX request.

  • Open the Firefox Console and find the Network tab.
  • While in the Network tab find the javascript (.js) file responsible for calling the PHP file that generates the JSON object.
  • Highlight the file by clicking on it.
  • While the file is still highlighted click on the XHR tab. This will cause the relevant .php file(s) to appear below the highlighted .js file.
  • Click on the PHP file of interest and find the Response tab in the appropriate corresponding box. It is in the viewport of this box that the object appears.
  • Click on the various objects, arrays, and other components of the object to learn how it is structured and to display the values.

Have a great weekend!

Roddy

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×