Error encountered while trying to retrieve the value following JSON parsing

I'm struggling with converting the value from the string below. I've attempted to parse it as JSON, but have had no success.

const val1 = "{a: '123'}";

console.log(typeof(val1)); // string

const a = JSON.parse(val1); // Error: Unexpected token a in JSON at position 1

const b = JSON.parse(JSON.stringify(val1)); 
console.log(b); // {a: '123'}
console.log(b.a); // ---> undefined

console.log(typeof(b)); // string -> How?

If I try

JSON.parse(b) -> It gives an error: Unexpected token a in JSON at position.

Could anyone provide insight on what mistakes I might be making?

Answer №1

Here is a solution for your issue:

const jsonText = '{"a": "123"}';
const parsedJson = JSON.parse(jsonText);

console.log(parsedJson.a);

The problem lies in the single quote present in your JSON string. To learn more about valid JSON syntax, please refer to this link.

You can solve this by using the following formats:

const jsonString1 = '{"a": "123"}';
const jsonString2 = "{\"a\": \"123\"}";

Answer №2

It seems like the issue lies within line #4 of your code

const copy = JSON.parse(JSON.stringify(data)); 

The problem arises from attempting to parse the result of

JSON.stringify("{x: 'abc'}")
This creates a "string within a string".

https://i.sstatic.net/xyz12.png

Just as mentioned in an earlier response, make sure the format of your json is accurate. Consider using a tool such as https://jsonlint.com/ to validate your json structure.

Answer №3

Revised the code provided below for verification.

    const value = '{"b": "456"}';

console.log(typeof(value)); // string

const x = JSON.parse(value); // x is now a JSON object

const y = JSON.parse(JSON.stringify(value)); // since value is already a string, this step is unnecessary
console.log(x); // {b: '456'}
console.log(x.b); // ---> changed to b
const z = JSON.parse(y);
console.log(typeof(y)); // string -> Double conversion to string but still remains as a JSON object
console.log(typeof(z)); // Need to use JSON.parse on y to convert it back to an Object

Answer №4

const val1 = "{a: '123'}";
console.log(typeof(val1)); // string
const a = JSON.parse(val1); // Gives Error:

This issue arises because the variable val1 is not a valid JSON string, as the property a and its value inside the object are not enclosed in double quotes. Once we correct this, it works as expected:

const val1 = '{"a": "123"}';
console.log(typeof(val1)); // string
const a = JSON.parse(val1); // It works!
console.log(a)


const b = JSON.parse(JSON.stringify(val1)); 
console.log(b); // {a: '123'}
console.log(b.a); // ---> undefined

The reason why b.a is undefined here is that b is not actually an object but a string:

const val1 = "{a: '123'}";
const b = JSON.parse(JSON.stringify(val1));
console.log(b); // {a: '123'}
console.log(typeof b); // string
console.log(b.a); // ---> undefined

This behavior occurs because

JSON.stringify(val1)

converts "{a: '123'}" to ""{a: '123'}"", adding extra double quotes around

val1</code which was already a string.</p>

<p>By applying <code>JSON.parse
to it, the double quotes are removed, resulting in the original string again.

const val1 = "{a: '123'}";
const val2 = JSON.stringify(val1);
console.log( val2 )   // "{a: '123'}" ... it's actually ""{a: '123'}""
console.log( typeof val2 )  // string

const val3 = JSON.parse(val2);
console.log( val3 )   // {a: '123'} ... it's actually "{a: '123'}"
console.log( typeof val3 )  // string

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

Satellizer failed to send the Authentication header to my API

Currently, I am working on a project locally with an API built in Laravel. Everything is functioning correctly - I can log in using Facebook, receive a JWT token from the API, and store it in local storage. However, even after logging in, my API calls do n ...

Is it feasible to assign a PHP $_SESSION variable to a JavaScript variable?

In my computing class, I am working on a game where the user needs to adjust settings for their robot before starting to play. I have created a separate PHP file for users to customize their robot's settings. I am curious if there is a way to assign ...

How can I assign a reference to a List component using react-virtualized?

Could someone help me with referencing the scrollable List in react-virtualized using a ref? I'm having trouble as my ref keeps showing its current attribute as undefined. Any tips on how to properly use a ref with react-virtualized List? This is wha ...

Issues with property methods not being invoked during JSON deserialization

Within the realm of my coding project, there exists a JSON class file that encompasses three distinct classes. Each class is structured in a similar manner: public class ManifestJSON : INotifyPropertyChanged { [JsonProperty("dataType")] private st ...

Having trouble accurately obtaining the height of a DIV element using jQuery

After trying to troubleshoot on my own, I ran into a roadblock due to my specific requirements not being met by existing solutions. The issue at hand is as follows: I have a sticky DIV element positioned to the left, nested within another DIV Element wit ...

Tips for collecting user input for nested JSON dictionaries when converting them into a dataframe

I've got 2 JSON files filled with nested JSON data. The structure of these files is as follows: JSON1 { "apple": { "price": { "type": "good", "value": 82.0, } }, "banan ...

Enhance your search experience with categorized autocomplete

Trying my hand at implementing a Jquery Autocomplete with categories and Ajax, Here's the javascript code I found on the Jquery UI website: <script> $.widget( "custom.catcomplete", $.ui.autocomplete, { _renderMenu: function( ul, items ...

The next.js application utilizing a custom server is experiencing rendering issues

Expanding my knowledge to next.js, I might be overlooking a simple aspect. My goal is to implement custom routes, so I crafted a server.js file and adjusted the command in my package.json to node server.js. Below is the entirety of the server.js file: con ...

Encountered an error while running npm run dev on a NextJS application due to an

Upon running the npm run dev command, the next app is displaying an error message: $→mmoLD;%g?wŷ↓▬ovH0a5*ؒl͛Siy☺rO7%L]%∟hk ^ SyntaxError: Invalid or unexpected token at wrapSafe (internal/modules/cjs/loader.js:988:16) at Module._comp ...

Signs that indicate you have reached the bottom of the page

Wondering how they achieve that cool effect on where the top line appears with a new logo when you scroll down? Is it done using a jQuery trick? How can you determine when a person has scrolled down a certain amount of pixels and then show them new HTML ...

Displaying JSON data in a tableview

I have successfully parsed JSON data using the NSJSONSerialization class and can see all the data in the console log. However, I am struggling to figure out how to display this data in a table view. Below is the code I have so far. Any help on how to show ...

Showcasing an HTML table using Material-UI

Currently, I have a list of issues being displayed in my browser using the material-ui code below: <Paper className={classes.root} elevation={4}> <Typography type="title" className={classes.title}> All Issues </Typography> ...

How to Use Vanilla JavaScript to Fetch a JSON File, Convert the Data into an Array, and Iterate Through Each Object

Imagine having a JSON file called map.json: { "images":{ "background": ["images/mountains.png","images/sea.png"] } } The goal is for JavaScript to retrieve "images/mountains.png" from map.json and us ...

Deactivate the button in the final <td> of a table generated using a loop

I have three different components [Button, AppTable, Contact]. The button component is called with a v-for loop to iterate through other items. I am trying to disable the button within the last item when there is only one generated. Below is the code for ...

A guide to efficiently managing updates and inserts with bulkCreate in node.js

Currently, I am utilizing node.js to facilitate the uploading of an excel file into a database. Furthermore, in my service, I am employing bulkCreate to efficiently upload the data into the mysql db. In order to provide more context, I will outline the str ...

Looking for a method to select checkboxes using PHP? Consider utilizing a value to achieve this task

What is the correct way to define the isset function? When written as shown here, PHP does not register the click. `if(!isset($_POST['checkbox1']) || !isset($_POST['checkbox2']) || !isset($_POST['checkbox']) ) { ...

Guide to storing user data retrieved from the LinkedIn API into an Angularjs controller with the help of a personalized service

Hey there, I'm currently diving into Angular and facing a challenge with saving user information from LinkedIn API to the controller's scope without directly passing it to my custom service. It seems like that might not align with the best practi ...

How does this particular save method function within the context of mongoose, without explicitly mentioning the specific database

Starting off, I have a main workspace folder called "Projects" Inside this folder, there are 2 subfolders: Models: 1) Something-model => const mongoose = require("mongoose"); const Schema = mongoose.Schema; const Something-Schema = new Schema({ n ...

Accessing a webpage solely by logging in prevents unauthorized access

My login page currently redirects to a page named gallery.html upon successful login. However, I have noticed that entering /gallery.html in the URL also directly accesses the secure page without logging in. Can anyone suggest an effective way to impleme ...

Dealing with unexpected modifications in a React class component

In short, I need to adjust the data in my class component before sending it to the server to match the API request format. To achieve this, I created a method called transformData within my class component which transforms the data extracted from the state ...