I struggle with parsing JSON data in JavaScript

After reviewing the post, I am still unclear about what is going on.

Although my variable "text" seems to be valid based on most JSON online data checkers, when I attempt to parse it, nothing happens.

Here's a snippet of example code:

<!DOCTYPE html>
<html>
<body>

<h2>Creating an Object from a JSON String</h2>

<p id="demo"></p>

<script>
var text = '{
"zipcodes": [
    {
        "zip": "22312",
        "city": "Alexandria",
        "state": "VA"
    },
    {
        "zip": "22030",
        "city": "Fairfax",
        "state": "VA"
    },
    {
        "zip": "22301",
        "city": "Tyson's Corner",
        "state": "VA"
    },
    {
        "zip": "20148",
        "city": "Ashburn",
        "state": "VA"
    }
]}';

obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.zipcodes[1].zip + " " + obj.zipcodes[1].city;
</script>

</body>
</html>

Answer №1

There are a couple of issues to address:

  1. JavaScript does not inherently support multi-line strings without using a continuation character (such as \ at the end of each line). While this can be done, it is more convenient to keep your JSON data on a single line.

  2. You are using single quotes for your string, but the string itself contains an unescaped '. To resolve this, simply escape the quote and everything should work correctly.

var text = '{ \
  "zipcodes": [\
    { \
      "zip": "22312", \
      "city": "Alexandria", \
      "state": "VA" \
    }, \
    { \
      "zip": "22030", \
      "city": "Fairfax", \
      "state": "VA" \
    }, \
    { \
      "zip": "22301", \
      "city": "Tyson\'s Corner", \
      "state": "VA" \
    }, \
    { \
      "zip": "20148", \
      "city": "Ashburn", \
      "state": "VA" \
    } \
  ]}';
  
obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.zipcodes[1].zip + " " + obj.zipcodes[1].city;
<div id='demo'></div>

Answer №2

Remember to keep the JSON on a single line and escape any apostrophes.

"McDonald\'s"

http://jsbin.com/xumiba/1/edit?html,js,console,output

var information = '{ "restaurants": [ { "name": "Chipotle",  "location": "123 Main St", "city": "Anytown", "state": "TX"}, { "name": "Chick-fil-A", "location": "456 Elm St", "city": "Othertown", "state": "CA"} ]}';

Answer №3

To ensure that each string new line is properly formatted and the ' character is escaped, it's necessary to use a backslash (\) at the end of every line. A sample code snippet demonstrating this is as follows:

var text = '{\
"zipcodes": [\
    {\
        "zip": "22312",\
        "city": "Alexandria",\
        "state": "VA"\
    },\
    {\
        "zip": "22030",\
        "city": "Fairfax",\
        "state": "VA"\
    },\
    {\
        "zip": "22301",\
        "city": "Tyson\'s Corner",\
        "state": "VA"\
    },\
    {\
        "zip": "20148",\
        "city": "Ashburn",\
        "state": "VA"\
    }\
]}';

obj = JSON.parse(text);

console.log(obj.zipcodes[1].zip + " " + obj.zipcodes[1].city);
document.getElementById("demo").innerHTML =
obj.zipcodes[1].zip + " " + obj.zipcodes[1].city;

If you wish to view this code in action, here is a link to a jsfiddle:

http://jsfiddle.net/0retway7/

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

Transform seconds into an ISO 8601 duration using JavaScript

Dealing with ISO 8601 durations can be quite tricky. Efficiently converting seconds to durations is my current challenge, especially in JavaScript. Stay tuned for my solution and the Jest test script coming up next. ...

Error with Firebase. Make sure the URL for your Firebase Realtime Database instance is set up correctly

Currently, I am utilizing the getServerSideProps function to retrieve data from my Firebase database for my Next.js application. This is how my code snippet appears: export async function getServerSideProps(context) { const session = await getSession( ...

Synchronized multiple file uploads using AjaxFileupload

Currently, I am working on implementing a feature to upload multiple files asynchronously. One of the functionalities I want to include is a SMTP client where users can select files, compose a message, and then send an email. I have tried using ajaxfileu ...

Optimal method for displaying content in Vue.js in read-only mode

I am currently working on a code snippet used to display messages exchanged between two users. <template> <main> <form action="" method="post" @submit.prevent="sendMessage"> <textarea name="message" id="messag ...

Can you provide instructions on converting .stl files to .png format using Python, as well as how to extract their dimensions?

Is there a way I can convert .stl files to .png format for preview purposes using Python? Additionally, how can I extract the dimensions of .stl files such as volume, height, and width? I currently view my .stl files with Three.js, but I am struggling to ...

Guide on passing the set[State] function to a trigger component that is not a descendent

Take a look at this diagram. ChildComponentB contains a state called stateX. In ChildComponentA, when a certain event occurs, it should modify the stateX in ChildComponentB. If ChildComponentA is a child component of ChildComponentB, passing the setStateX ...

Outputting a string from a Django template without using HTTPResponse

Is it possible to populate a template using objects from a query set without having to return a HTTPResponse in Django? One view currently has the following code: return render_to_response('entry.json', {'entry_list':r}, mimetype="appl ...

Replace a function within the UI-Bootstrap framework

Incorporating the angular-bootstrap library into my app via bower has been a game changer. Although I am currently stuck with an (outdated) version that includes a pesky bug, upgrading is not yet feasible in my scenario. I considered inserting a customiz ...

Endless waiting in Node JS

I am working on a program that extracts data from a database. However, I am encountering an issue where the program gets stuck in an infinite loading loop. router router.get('/', (req, res) => { res.render('/music', '', ...

The Vue component appears to be missing from the HTML code

I recently began learning Vue.js in school, and for my first assignment I need to print a h2 from a Vue component. However, I am having trouble getting it to work. Below is the code for the Vue component that I have created. var app = new Vue({ ...

Converting an array into a string, transitioning from PHP to JavaScript

Hey everyone, I'm currently working on passing an array to a JavaScript file and encountering this error: An exception has been thrown during the rendering of a template ("Notice: Array to string conversion"). What I need is: data: ['2017/7&a ...

What steps should be taken to safely sanitize untrusted JSON data before parsing it with JSON.parse method

How can we properly sanitize a user-provided JSON string to prevent any vulnerabilities before executing JSON.parse(untrustedString)? My main concern revolves around prototype pollution, but I'm also interested in knowing about any other potential ri ...

What is the most effective way to determine which radio button is currently selected in a group with the same name using JQuery?

<form class="responses"> <input type="radio" name="option" value="0">False</input> <input type="radio" name="option" value="1">True</input> </form> Just tested: $('[name="option"]').is(':checked ...

Combine an entire Yeoman project built with AngularJS into a single file for seamless integration

Currently in the process of creating a form using Yeoman and AngularJS version 1.2.27. The goal is to have this form easily integrated into any client's web page. By generating a distribution folder with grunt, containing various files like JS, CSS, ...

Encountering issue while attempting to read JSON file with JSON Simple Library

Attempting to parse the JSON file below in Java. Here is the sample JSON data: { "names": [ { "no": 1, "name": "John" }, { "no": 2, "name": "Paul" } ], "new_name ...

What is the best way to choose a file in an input field of type file when writing selenium test cases

When using selenium test cases, I encountered the need to select a file from an input type="file". To achieve this, I utilized the following method. browser.element(By.id('fileupload')).click(); By executing this line of code, a popup window wa ...

angular determine if a column exists within a matCellDef iteration

Is there a way to check a column in an ng for loop in Angular without using the logic "{{element[p.key] != null ? '$' : ''}}" for a specific column or excluding a specific column? View image description here #html code <table mat-t ...

How can I avoid C3.js legends from overlapping when hiding or showing a div?

Every time I visit a specific page, a simple chart is automatically generated: function displayOptions() { $("#div1").show(); chartRef.flush(); } function displayChoices() { $("#div1").show(); } $("#div1").hid ...

Building a scrollable dropdown menu with Bootstrap 5: A step-by-step guide

The search for suitable code examples for scrollable dropdown menus compatible with Bootstrap 5 has been challenging. Are there any contemporary methods available to achieve this functionality seamlessly? ...

React-router Link failing to load content

In my current development setup, I am utilizing React and Rails with AWS S3 to create a platform similar to YouTube. I've encountered an issue with navigating to different video content within a watch page using react-router. When clicking on a link t ...