Converting a string to JSON format with JavaScript

My string is structured in JSON format like this:

"{""c1"": ""value1"", ""c2"": ""value2""}"

After storing it in an SQLITE database, I use the following Javascript code to retrieve it back as JSON:

  var req= "SELECT json_column from my_table";
  var result = execSQL(req);
  for (var index in res) {
    var row= res[index];
    consoleLog("test getad ", JSON.parse(row["json_column "]));

Unfortunately, I encounter an error message :

<JSContext: 0x1c0044aa0> SyntaxError: JSON Parse error: Expected '}' 

I have spent a considerable amount of time trying to troubleshoot this issue with no success. If necessary, I am open to modifying the string format in order to successfully retrieve it from the SQLITE database as a valid JSON object. Thank you for your help.

Answer №1

Your provided string is not a valid JSON format, but here is an example of a valid JSON string based on its content:

'{"c1": "value1", "c2": "value2"}'

In JSON format, key/value pairs are enclosed in single double quotes ", and the entire string is wrapped in single quotes '. If you were to use double quotes for the whole string, you would need to escape the inner ones as shown below:

"{\"c1\": \"value1\", \"c2\": \"value2\"}"

For more detailed information about JSON formatting, you can refer to this post:

  • What is the correct JSON content type?

Here is a code snippet demonstrating the outputs of different JSON formats:

// Outputs for correctly formatted JSON strings

// Correctly formatted JSON
console.log( JSON.parse('{"c1": "value1", "c2": "value2"}') );

// Correctly formatted JSON with outer double quotes and inner escaped ones
console.log( JSON.parse("{\"c1\": \"value1\", \"c2\": \"value2\"}") );

// Your string wrapped with single quotes and inner double quotes replaced with single ones
console.log( JSON.parse('{""c1"": ""value1"", ""c2"": ""value2""}'.replace(/""/g, '"')) );


// These will generate script errors

// Your string wrapped with single quotes
console.log( JSON.parse('{""c1"": ""value1"", ""c2"": ""value2""}') );

// Your string as is - had to comment out due to potential crash
//console.log( JSON.parse("{""c1"": ""value1"", ""c2"": ""value2""}") );

Answer №2

The format of your string is incorrect, which is causing JSON.parse() to not be able to read it.

Here is your current string:

"{""c1"": ""value1"", ""c2"": ""value2""}"

Try changing it to this format:

'{"c1": "value1", "c2": "value2"}'

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

Library for adjusting the x axis scaling accurately

I need to find a JavaScript chart library that can support lines and zooming for handling a large amount of data. One issue I have encountered with other libraries is scaling the x-axis based on date and time data provided in strings: y=[43,56,34,63....] ...

Struggling to grasp the syntax, trying to invoke a JavaScript function using an input button

I'm really struggling to grasp the xhtml syntax involved in calling a function with an input button. Despite my efforts to find a clear explanation, this concept still eludes me. Within the snippet of code from my book that I've been referencing ...

Troubleshooting a dysfunctional Vue.js component

I am currently facing a challenge in getting components to function properly. Interestingly, without the component, everything seems to be working fine (as per the commented code). Here is my HTML snippet: <strong>Total Price:</strong> <sp ...

Controlling ever-changing routes using AngularJS

My AngularJS app (Angular v1) has a secure login system in place. Users who are not authenticated can only access the login page, forgotten password page, and cookie policy. I am utilizing ngRoute as shown below: $routeProvider .when('/login ...

Why does app.post function while router.post does not seem to work?

I have encountered an issue while logging in with React on the front end. The process goes to my node/Express/Passport backend and I am able to successfully log in when it reaches the backend. However, I am facing difficulties in communicating that informa ...

Expand and Collapse Button for Customizing Table Height Individually

I trust everything is going smoothly. A challenge I'm facing involves implementing a button to expand a specific row within a table. Currently, clicking the "show more/show less" button extends all rows when the goal is to do it for each individual ta ...

JavaScript button not responding to click event

Here is the initial structure that I have: <section id="content"> <div class="container participant"> <div class="row"> <div class="input-group"> <div class="input-group-prepend"> ...

Function that returns an Observable<Boolean> value is null following a catch block

Why is the login status null instead of false in this method? // In the method below, I am trying to return only true or false. isLoggedIn(): Observable<boolean> { return this .loadToken() .catch(e => { this.logger ...

Creating dynamic HTML elements by utilizing both jQuery and native JavaScript within the DOM

I have an old application that I'm revamping, and instead of using the node's id, I want to apply the DOM structure to its class. Here is a snippet of my code where I am attempting to combine jQuery (selecting the node by its class) with the exi ...

Having difficulty linking the Jquery Deferred object with the Jquery 1.9.1 promise

I have been developing a framework that can add validation logic at runtime. This logic can include synchronous, asynchronous, Ajax calls, and timeouts. Below is the JavaScript code snippet: var Module = { Igniter: function (sender) { var getI ...

Displaying and hiding a div element using Vue.js dynamically

I have a scenario with two different sized divs: <div class = "bigger"> </div> <div class = "smaller"> </div> The goal is to hide the bigger div and show the smaller div when the screen width is ...

The functionality of the AJAX Script is failing to load properly on mobile devices

Currently, I am undertaking a project that involves ESP32 Arduino programming to create a webpage where users can interact with buttons to activate relays. Additionally, I have implemented a slider using a short script. This project is inspired by the ESP3 ...

Looking for guidance on sending data from a JS file to HTML using Nodejs? Seeking advice on various modules to achieve this task effectively? Let's

Looking for advice on the most effective method to transfer data from a JS file (retrieved from an sqlite db) to an HTML file in order to showcase it in a searchable table. My platform of choice is NodeJS. As a beginner, I am willing to put in extra time a ...

Unable to arrange an array of JavaScript objects retrieved via an Angular REST request

I'm currently encountering an unusual issue with sorting an array of JavaScript objects. While sorting some dummy data works fine, I am unable to sort the array when fetching the object through an Angular REST call. The structure of the message is as ...

Exporting a function to another class using the default export is a common practice

I'm working with two classes, Orders.js and api.js. In api.js, I need to invoke a function called ShowAlertWithDelay. However, due to the existence of a default export named mapStateToProps, I am unable to declare another export. Below is the code sni ...

Which SSO framework works best for integrating Facebook and Twitter logins?

I own a website and I'm looking for a way to let users leave reviews and rate products. I need an SSO system that allows them to sign in with their Facebook or Twitter accounts and ensures each user is uniquely identified so they can't rate produ ...

The concept of immutability is crucial when utilizing a for-in loop to append an object to an array

Within my code, I have a nested loop structure consisting of a for of with a for in loop inside it. This setup retrieves information from a Neo4J database. By utilizing the Object.assign method, I am able to transfer a property from the fetched object into ...

Iterate through a collection of nested objects and check them against an object contained within an array

I'm facing a frustrating issue in Firebase where I am required to compare an object returned to me with an array. I need assistance in completing this method: const removeAlreadySeenUsersFromQueue = (newUsers, likedUsers) => { } The scenario is ...

Press the button to update several span elements

Imagine I have multiple span elements like this: <span>A</span> <span>B</span> <span>C</span> <span>D</span> and a div element (which will be converted to a button later) named "change". <div id="chan ...

The Jquery Index() method often results in a return value of -

I have developed a function in JavaScript that creates HTML content. Within the test(test1) function, I am checking if test1.Test__c is null and changing the color accordingly. The line ".table-striped > tbody > tr.testcss" is responsible for changin ...