I'm feeling a bit lost with this JSON example - specifically with JSON.parse, JSON.stringify, as well as localStorage.setItem

As a beginner in learning JSON, I find that W3schools does not provide clear explanations of what each line of code does. While I can interpret some parts, there are sections that still remain unclear to me.

// Data storage process:
1. myObj = {name: "John", age: 31, city: "New York"};
2. myJSON = JSON.stringify(myObj);
3. localStorage.setItem("testJSON", myJSON);

// Retrieving stored data:
4. text = localStorage.getItem("testJSON");
5. obj = JSON.parse(text);
6. document.getElementById("demo").innerHTML = obj.name;

I understand the purpose of line one, which is basically creating variables for storage. Line two seems straightforward as it converts variable storage into a string format. However, line three's operation is not entirely clear to me and I would appreciate an explanation.

Lines four and five also pose some confusion for me. On the other hand, line six is much easier to comprehend.

To summarize, I would like clarification on lines 2, 3, 4, and 5 functionality.

Answer №1

I will break down each line step by step.

Saving Process

  1. myObj = {name: "John", age: 31, city: "New York"};
    • This line initializes an object with the name, age, and city properties.
  2. myJSON = JSON.stringify(myObj);
    • This line converts the JavaScript object into a JSON string format which is compatible with applications that support JSON.
  3. localStorage.setItem("testJSON", myJSON);
    • Modern browsers provide a localStorage API for storing data within the browser. This line stores the JSON string in the localStorage for future reference.

Retrieving Process

  1. text = localStorage.getItem("testJSON");
    • This line retrieves the previously stored JSON string from the localStorage.
  2. obj = JSON.parse(text);
    • Here, the retrieved JSON string is converted back to a JavaScript object through parsing.
  3. document.getElementById("demo").innerHTML = obj.name;
    • This line accesses the name property of the parsed object and displays it in the demo element on the webpage.

Answer №2

I understand the purpose of line one; it simply stores variables.

Affirmative.

I believe line two converts the stored variables into a string.

Correct assumption.

The meaning of line three eludes me.

For more information on line three, please refer to the MDN localStorage documentation. This line demonstrates how you can store an object in localStorage for future use when revisiting the page, similar to what is done in Line 4.

Line 5 reverses the process of Line 2, taking a valid JSON string and returning a JavaScript object.

Answer №3

Below is the breakdown of the process:

// Defining an object with properties for name, age, and city
1. myObj = {name: "John", age: 31, city: "New York"};

// Serializing the object into a string format using JSON.stringify
2. myJSON = JSON.stringify(myObj);

// Storing the serialized object in localStorage under the key 'testJSON'
3. localStorage.setItem("testJSON", myJSON);

// Retrieving the data from localStorage using the key 'testJSON'
4. text = localStorage.getItem("testJSON");

// Parsing the retrieved string back into an object 
5. obj = JSON.parse(text);

// Updating the content of element #demo in the DOM with the name property of the object
6. document.getElementById("demo").innerHTML = obj.name;

Answer №4

  • Line 2 involves converting your object into a string for storage purposes...
  • ... Within the realm of local storage, which can be likened to a database (line 3).
  • Line 4 invokes the local storage to retrieve the previously saved value,
  • Since it is in serialized form (stored as a string), you must parse it ("transform it") back into a JavaScript object to make it usable (using JSON.parse).

Answer №5

At the start, a variable object is created.

The next step involves converting the object to JSON format.

Following that, the object is stored on localstorage with a key value pair, where the key is designated as "testJSON".

To retrieve the localStorage, the specific key is utilized.

After retrieving the data, it is parsed and converted back into an object.

Lastly, the element id value within the object is set under the key "name".

Answer №6

Before anything else, it's important to highlight the tutorial you are mentioning clearly states in bold red letters "Further information on JSON.parse() / JSON.stringify() will be covered later in this tutorial.

To summarize, stringify() is a method used to transform a json object into a string format. On the other hand, parse() is a function that analyzes the string and generates an output from it.

Answer №7

Window.localStorage

localStorage is a key component of the Web Storage API, allowing for data storage without an expiration date, unlike sessionStorage. This functionality is supported by most modern browsers and enables the storage of key/value pairs for later use. It serves as a replacement for certain cookie usage scenarios.

The commonly used methods with localStorage are localStorage.getItem() and localStorage.setItem(), which retrieve and set data values associated with specific keys, respectively.

One typical application of localStorage.setItem() is when there is a need to retain data for future access, ensuring it remains available even after a page refresh or navigation to another page. To retrieve stored data, localStorage.getItem() is utilized.

In addition to localStorage, there is also sessionStorage, similar in function but with the distinction that sessionStorage includes an expiration period, making it more suitable for temporary data storage.

Important: It is advisable to refrain from storing sensitive information using this method, as the data is not secure.

JSON.parse and JSON.stringify

JSON.parse converts JSON string format into an object, while JSON.stringify performs the inverse operation of converting an object into a string.

When dealing with external sources providing data in string format, JSON.parse is typically employed to transform the string into an object usable within JavaScript code for data manipulation. On the other hand, JSON.stringify is useful for converting manipulated object properties back into a string for storage purposes.

For further information on the Web Storage API, please visit:

https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API

More details on JSON and its related methods JSON.stringify and JSON.parse:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON

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

What is the best way to display a JavaScript object array on the screen

As someone who is new to JavaScript, I have a JavaScript object array that I would like to print the values of in the browser. However, I am unsure of how to do this without using document.write(vehicle); var vehicle = [{name:'Van',wheel:4,cha ...

Why aren't the kittens loading in Next Js?

Following the guidance in the Next Js documentation, I created a next.config.js file to inform Next Js that I want to incorporate kittens into my app. The resource for the kittens can be found at: This is how the next.config.js file appears: module.expor ...

Find a partial match in the regular expression

I am currently working on filtering a list of names using regular expressions (regex). The data is stored in the following format: [ { "firstName": "Jhon", "lastName": "Doe", }, ... ] Users have the option t ...

Pagination activates on the second tap

Check out my example on jsFiddle: https://jsfiddle.net/0se06am5/ class Pagination extends React.Component { constructor(props) { super(props); this.state = { current: 1 }; this.items = ['a', 'b', 'c&ap ...

Angular confirmation page following successful HTTP POST request to Web API

First question here... I have been given the task of improving an Angular application, even though I am starting with zero experience in Angular. While I do have some background in JavaScript, I mostly work with Java (JSP's and yes, JavaScript). Despi ...

Having trouble importing a React component from a different directory?

I have included the folder structure for reference. Is there a way to successfully import the image component into the card component? No matter which path I try, I keep encountering this error: ./src/Components/Card/Card.js Module not found: Can't ...

Journey Swiftly Control

I have a question. Is it possible to manipulate routes in Express? Can I assign multiple routes to the same get or post request when providing an address? module.exports = function (app) { var controller = app.controllers.maps.cliente; app.route(&apos ...

Encountering an issue with html2canvas: receiving an error message stating "object

To print the div using Javascript, I encountered an issue with the generated barcode not appearing in the printed page. This led me to use the html2canvas approach to 'render' the div before printing it out. Here is the code snippet: HTML: < ...

Adding code containing various Google Maps elements in a fresh browser window using JavaScript

I've encountered an issue while trying to create a new page with a Google map and title based on the button clicked. Interestingly, when I copy/paste the HTML in the "newhtml" variable into an actual HTML file, it works perfectly fine. However, it doe ...

I'm experiencing an "existing database with different casing already exists" error, even though I have no intention of creating a new database

My goal is to include a new word in a database called "wordsDb" within a collection named "wordsCollection": dbName = "wordsDb"; collectionName = "wordsCollection"; connectionUri = //... (secret) async add(word) { try { ...

Displaying jsp variable in the browser console

When working in JSP, using <p>${ob}</p> to retrieve an object can be challenging due to the size of the object. Is there a way to utilize JavaScript to print it instead? Keep in mind that since this involves handling email content, JavaScript ...

Issue with parsing JSON data in AgGrid

I'm currently utilizing Ag-grid within my Angular project. The rowData is populated with data from a JSON file stored in the assets folder, which is fetched using HttpClient. However, I'm encountering an issue where the data fails to load and an ...

When employing `queryParams` in Angular routing, the URL will automatically replace `%` with `%25`

When trying to use queryParams for navigation in Angular routing, I encountered an issue. <a routerLink='/master' [queryParams]="{query:'%US',mode:'text'}"><li (click)="search()">Search</li></a> The d ...

Dealing with nested try/catch mechanism in NodeJS

As a Node.js novice, I am delving into the realm of coding two nested try/catch blocks with retry logic. My goal is to have the inner try/catch block send any caught errors to the outer catch block, where I will increment a retry count by 1. Once this co ...

Unable to display decoded JSON data retrieved using file_get_contents

Currently, I have integrated the Google Site Verification reCAPTCHA API into my website. $json = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$response."&remoteip=".$ip); After making this call, ...

Error: Conversion of "2018-01-01-12:12:12:123456" to a date is not possible for the 'DatePipe' filter

<td>{{suite.testSuiteAttributes && suite.testSuiteAttributes.modifiedTimestamp | date: 'yyyy-MM-dd' }} </td> I am trying to display the date in the "05-Feb-2018 11:00:00 PM CST" CST format, but I keep getting an ...

Is there a way to use jQuery to eliminate divs that contain multiple identical data values?

Is there a way to accomplish this? <div class="chat_timestamp_group" data-date="08-March-2016"></div> <div class="chat_timestamp_group" data-date="08-March-2016"></div> <div class="chat_timestamp_group" data-date="14-March-2016" ...

Searching for multiple keywords across multiple fields using Elastic search

I've been working on creating a query in Elastic search to search within the text of multiple fields, such as Title and Description. My goal is to search for specific keywords like "obama", "world", and "news" across these fields. I found some informa ...

Unusual hue in the backdrop of a daisyui modal

https://i.stack.imgur.com/fLQdY.png I have tried various methods, but I am unable to get rid of the strange color in the background of the Modal. Just for reference, I am using Tailwind CSS with Daisy UI on Next.JS. <> <button className='btn ...