www.webdeveloper.com
Results 1 to 10 of 10

Thread: JSON.parse/JSON.stringify Array - Remove special characters

  1. #1
    Join Date
    Mar 2013
    Posts
    13

    JSON.parse/JSON.stringify Array - Remove special characters

    I am using the following code:

    HTML Code:
        // History Information Array
        var historyInfo = localStorage.getItem("history");
        if (!historyInfo) {
            historyInfo = [];
        } else {
            historyInfo = JSON.parse(historyInfo);
        }
        historyInfo.push("You travelled " + distance + " mile(s) in " + duration + " on " + timestamp + "." + "<br>");
    	
        localStorage.setItem("history", JSON.stringify(historyInfo));
    This works fine!

    However, when I return the results to the web page using
    HTML Code:
    localStorage.getItem("history")
    it returns something like this:

    ["You travelled 0 in mile(s) 00:00.05 on 11 April 2013 18:02:33.
    ","You travelled 0 mile(s) in 00:00.08 on 11 April 2013 18:03:31.
    "]

    How can I remove the square brackets and quotation marks?

  2. #2
    Join Date
    Dec 2012
    Posts
    264
    The square brackets indicate that it's an array, so your example there is an array containing 2 strings.

    If you want to output both of the strings you could do something like this

    HTML Code:
    for(var i = 0; i < historyInfo.length; i++) {
        document.body.innerHTML += historyInfo[i];
    }

  3. #3
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    22,326
    This is not PHP. I'll move it to the JavaScript forum, since that's what it appears to me to be.
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  4. #4
    Join Date
    Mar 2013
    Posts
    13
    iBeZi, the code you provided should work. However, I am using the following code:

    function clearWatch(position) {
    document.getElementById('start').disabled = false;
    document.getElementById('stop').disabled = true;
    navigator.geolocation.clearWatch(position);
    endTime = new Date();

    // Duration Calculator
    var difference = endTime - startTime;
    var diffSeconds = difference / 1000;
    var HH = Math.floor(diffSeconds / 3600);
    var MM = (Math.floor(diffSeconds % 3600) / 60).toFixed();
    var duration = ((HH < 10) ? ("0" + HH) : HH) + ":" + ((MM < 10) ? ("0" + MM) : MM);

    // History Information Array
    var historyInfo = localStorage.getItem("history");
    if (!historyInfo) {
    historyInfo = [];
    } else {
    historyInfo = JSON.parse(historyInfo);
    }
    historyInfo.push("You travelled " + distance + " mile(s) in " + duration + " on " + timestamp + "." + "<br>");

    localStorage.setItem("history", JSON.stringify(historyInfo));
    }

    // localStorage
    if (typeof (Storage) !== "undefined") {
    if (localStorage.getItem("history") === null) {
    document.getElementById("history").innerHTML = "There are currently no records to display.";
    } else {
    document.getElementById("history").innerHTML = localStorage.getItem("history");
    }
    } else {
    document.getElementById("history").innerHTML = "Your browser does not support the localStorage API.";
    }

    As you can see, I'm using 2 functions. When I apply the code you provided it doesn't work. Any ideas?

  5. #5
    Join Date
    Dec 2012
    Posts
    264
    In this part

    Code:
    if (localStorage.getItem("history") === null) {
    document.getElementById("history").innerHTML = "There are currently no records to display.";
    } else {
    document.getElementById("history").innerHTML = localStorage.getItem("history");
    }
    You need to parse the JSON stored in the local storage before outputting each item from the array to the history element

    Code:
    if (localStorage.getItem("history") === null) {
    document.getElementById("history").innerHTML = "There are currently no records to display.";
    } else {
    var historyArray = JSON.parse(localStorage.getItem("history"));
    for(var i = 0; i < historyArray.length; i++) {
    document.getElementById("history").innerHTML += historyArray[i]+" ";
    }
    }

  6. #6
    Join Date
    Mar 2013
    Posts
    13
    iBeZi, don't worry! I resolved this problem by moving the History Information Array outside of the clearWatch function. Success!

    I will ask one more question. Is there anyway to append a localStorage.removeItem(key) button to each record? And if so, how could I incorporate it within my existing code? Thanks

  7. #7
    Join Date
    Dec 2012
    Posts
    264
    You could do it by making a button for each record, making a note of which index that record appears at in the history array (maybe as a data attribute on the button), then when the button is clicked splice that record from the history array then save and update the record list.

  8. #8
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    Quote Originally Posted by iBeZi View Post
    You could do it by making a button for each record, making a note of which index that record appears at in the history array (maybe as a data attribute on the button), then when the button is clicked splice that record from the history array then save and update the record list.
    that sounds dangerous; you forgot to instruct that the indices need rebuilt+ re-rendered every deletion (not just saved), or else the splice will make further delete buttons delete the wrong ones.
    Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com

  9. #9
    Join Date
    Dec 2012
    Posts
    264
    Well when I said save and update the records list I meant outputting the list with buttons again with the new array, something like this http://jsfiddle.net/pQ5R2/

  10. #10
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    cool. i kinda mis-read your post and just wanted to be safe... cheers!
    Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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

"

"

X vBulletin 4.2.2 Debug Information

  • Page Generation 0.09995 seconds
  • Memory Usage 2,947KB
  • Queries Executed 15 (?)
More Information
Template Usage (35):
  • (1)SHOWTHREAD
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (1)ad_thread_first_post_content
  • (1)ad_thread_last_post_content
  • (2)bbcode_code
  • (3)bbcode_html
  • (1)bbcode_quote
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (10)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (10)postbit
  • (10)postbit_onlinestatus
  • (10)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (26):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (73):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_postinfo_query
  • fetch_postinfo
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • tag_fetchbit
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates