SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Aug 2011
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Using JSON.parse() is returning [object] and not the original input

    Hello
    I am storing some coordinates in a database, I do this using JSON.stringify method to convert an array of coords into a string. This works fine but when I try to reload the coords using JSON.parse() I don't get the original coords back instead I get [object Object],[object Object].

    here is the code.
    HTML Code:
    <script type="text/javascript" src="json2.js"></script>
    Code:
    function save_route()
    {
    	alert(path);
    	var str = JSON.stringify(path);
    	document.dataForm.routeMarkers.value = str;
    	alert(str);
    }
    this converts an array of coords eg (51.50439265195253, -3.3535325679687276),(51.53259269613245, -3.2134568843749776)

    into

    [{"Oa":51.50439265195253,"Pa":-3.3535325679687276},{"Oa":51.53259269613245,"Pa":-3.2134568843749776}]

    Code:
    function load_route(){
    	var loadStr = document.dataForm.routeMarkers.value;
    	alert(loadStr);
    	loadPath = JSON.parse(loadStr);
    	alert(loadPath);
    }
    when I try use this instead of getting the original coords back i get
    [object Object],[object Object]

    (the alerts are just to see what is going on)

    Thanks for any help

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,189
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    When you use JSON.parse it returns the string back to its original state which is an object, all you need to do is use something along the lines of the following example.

    Code JavaScript:
    var loadPath = JSON.parse(loadStr);
    alert(loadPath[0].Pa); // Returns the second result of the first array

  3. #3
    SitePoint Member
    Join Date
    Aug 2011
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks SgtLegend
    I thought that after I parsed the string back then the alert would be exactly the same as is was before being stringified, but what you said was right and has got the code working, so thanks alot.

  4. #4
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,189
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    No problem


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •