javascript Initiate JSON parsing with preset value

In order to parse JSON into a JavaScript object with data, I am providing a simple example below:

var IsTrue = true;
var Number = 9;
var Object = { a : 1};
var Array = [10,6];

var jStr = '{"ask" : IsTrue, "value" : Number, "obj" : Object, "arr" : Array}';
var js = JSON.parse(jStr);
console.log(js);

You can find my work on this in the following jsfiddle link: http://jsfiddle.net/n4tLgp5k/1/

However, when trying to execute this code snippet, I encountered an error message:

Uncaught SyntaxError: Unexpected token I

My goal is to successfully parse JSON into a JavaScript object, having the variables in the object initialized with values from previously initialized variables.

Answer №1

If you have a reference to a variable inside a string, you cannot parse it using JSON.parse(). Instead, convert the string to valid JSON by using JSON.stringify().

var IsTrue = true;
var Number = 9;
var Object = {
  a: 1
};
var Array = [10, 6];

var jStr = '{"ask" : ' + JSON.stringify(IsTrue) + ', "value" :' + JSON.stringify(Number) + ', "obj" : ' + JSON.stringify(Object) + ', "arr" : ' + JSON.stringify(Array) + '}';
var js = JSON.parse(jStr);
console.log(js);


If you only need to create the object, you can useobject literals. If you need a JSON string, you can use JSON.stringify()

var IsTrue = true;
var Number = 9;
var Object = {
  a: 1
};
var Array = [10, 6];

var js = {
  ask: IsTrue,
  value: Number,
  obj: Object,
  arr: Array
};

console.log(js);


There is also a way to achieve this using eval(), but it is not recommended due to security reasons.

Why is using the JavaScript eval function a bad idea?

var IsTrue = true;
var Number = 9;
var Object = {
  a: 1
};
var Array = [10, 6];

var jStr = '{"ask" : IsTrue, "value" : Number, "obj" : Object, "arr" : Array}';
var js = eval('(' + jStr + ')');
console.log(js);

Answer №2

Make sure you have a clean string to process properly.

let isTrue = true,
    numValue = 9,
    objValue = { key : 1},
    arrValue = [10,6];

let jsonString = {"ask" : isTrue, "value" : numValue, "obj" : objValue, "arr" : arrValue};
let parsedJsonString = JSON.parse(JSON.stringify(jsonString));
console.log(parsedJsonString);

However, the reasons behind this are unclear.

Answer №3

Instead of unnecessarily using a string, consider utilizing an object literal in your code like the example below:

var IsTrue = true;
var NumberValue = 9;
var ObjectLiteral = { a : 1};
var ArrayItems = [10,6];

var jsCode = {
    "ask" : IsTrue, 
    "value" : NumberValue, 
    "obj" : ObjectLiteral, 
    "arr" : ArrayItems
};
console.log(jsCode);

Avoid using reserved type names like Number, Object, and Array as variable names. This practice not only risks causing confusion but may also lead to errors in your code. Be mindful of naming conventions for better readability and maintenance.

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

Tips for serializing an embedded struct to a JSON string using the String() method

package main import ( "fmt" "encoding/json" ) type Ticket struct { From string To string } func (t Ticket) String() string { return fmt.Sprintf("%s - %s", t.From, t.To) } type Passenger struct { Name string `json:"Name"` ...

What is the best way to pass card data between Vue.js components?

My application consists of two components: DisplayNotes.vue, which displays data in card format retrieved from the backend, and UpdateNotes.vue, which allows users to update existing data by opening a popup. The issue I'm facing is that when a user cl ...

Is there a way to track and monitor the ngRoute requests that are being made?

I am in the process of transferring a fairly large Angular 1.6 application from an old build system to Yarn/Webpack. Our routing is based on ngRoute with a complex promise chain. While sorting out the imports and dependencies, I keep encountering this err ...

How to Utilize the Vue Instance With the 'this'

Trying to implement this in my VueJs methods results in an error message: this is undefined It seems like arrow functions may not be suitable as their this does not bind to the expected context. Switching to a regular function still causes the same err ...

Avoiding drag events in hammer.js until the previous event is finished

I've been working on a basic photo gallery that switches images during a drag event. However, I'm encountering an issue with the iOS7 browser where the drag event gets triggered multiple times when dragging left or right. I attempted to use a glo ...

Error encountered in React Material UI: Appbar - TypeError occurred when attempting to read properties that are undefined (specifically, reading '100')

Currently, I am working on developing a multi-step form using Material UI components. However, upon importing the necessary components, an error is being displayed in my code snippet: import React from 'react'; import { ThemeProvider } from &a ...

Adjusting the sound levels of an HTML audio element using JavaScript

I'm looking to adjust the volume of an <audio> element when a user clicks on an image. HTML: <div id="cloud"> <img name="jsVolumeButton" src="images/cloud.png" width = "140px"/> </div> <audio id="player" src="sounds/rain. ...

Utilizing the power of Vue Router with DataTables

I am currently facing an issue where I want to include links or buttons in my DataTable rows that can navigate to a vue route when clicked. The straightforward approach would be to add a normal <a> element with the href attribute set to "/item/$ ...

Is it possible for individuals external to access my API to submit requests?

Currently, I am diving into the world of full stack development. I have created a basic application using React for the frontend and set up a simple REST API on my express web server to handle specific routes. For instance, accessing api/users will provid ...

What is the best way to identify the position of an element in an array given my specific circumstances

I am trying to utilize the ng-repeat directive in order to display an array. Here is what I have: <div ng-repeat="stu in school"> <div>{{stu.name}}</div> <div>{{stu.grade}}</div> </div> JavaScript $scope.scho ...

Error in the syntax containing ?callback=jQuery1113

I'm attempting to initiate a simple JSONP query: <html> <head> <script type="text/javascript" src="js/jquery1.js"></script> <script> $(document).ready(function(){ $.ajax({ ...

Issue with reCAPTCHA callback in Firebase Phone Authentication not functioning as expected

I have been working on integrating phone authentication into my NextJS website. I added the reCAPTCHA code within my useEffect, but for some reason, it does not get triggered when the button with the specified id is clicked. Surprisingly, there are no erro ...

How can I switch the visibility of two A HREF elements by clicking on one of them?

Let me break it down for you in the simplest way possible. First off, there's this <a href="#" id="PAUSE" class="tubular-pause">Pause</a> and then we have a second one <a href="#" id="PLAY" class="tubular-play">Play</a> Al ...

Restrict the Angular ng-repeat directive to specific rows only

Suppose we have a JSON dataset listing all languages of books: $scope.data = [{ "title": "Alice in wonderland", "author": "Lewis Carroll", "lang": ["en"] }, { "title": "Journey to the West", "author": "Wu Cheng'en", "lang": [" ...

Navigating with Vue Router in a Nuxt JS vuex Store

In my app, I'm currently developing a login/register system using Firebase and Vuex for authentication and database management. Within Nuxt JS, I have implemented actions to create a user, log them in, and sign them out. After a successful registrati ...

Searching and updating a value in an array using JavaScript

I need help solving a Javascript issue I'm facing. I'm working on an e-commerce project built in Vue, and I want to implement the selection of product variants on the client-side. The data format being sent to the backend looks like this: { & ...

Field Invalid in Asana

I am trying to send the following JSON data to asana's "tasks" endpoint using a POST request. { "data": { "options": { "fields": [ "name", "notes" ] }, "workspace": & ...

Tips for handling the data sent to an API

Before continuing: This question is NOT about accessing a REST API. I am NOT inquiring about how to interact with the endpoint, sending data to it, and parsing the JSON received. Instead, my inquiry pertains to setting up that endpoint in vbScript. I am s ...

JQuery continuously firing off AJAX requests

Currently, I am experimenting with using a Jquery Ajax request to incorporate an AutoComplete feature. This involves utilizing ElasticSearch on the backend for data retrieval. This is what my autocomplete.html looks like: <!DOCTYPE html> <html l ...

`Maintaining Json data in a structured container`

Can someone assist me with combining multiple JSON files in a dictionary and extracting specific fields? I have a set of corrupted JSON files containing Twitter data where each line needs to be read individually. Below is the code snippet I am using: im ...