Extract data from JSON using the parse function

After utilizing the function JSON.stringify(), I have obtained this JSON:

{"get":"function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if('object'==typeof g)for(h in g)i[h]=g[h];i.url=f}else if('object'==typeof f)for(h in f)i[h]=f[h];return i.type=i.type||d,i.oauthio={provider:a,tokens:b,request:c},e.http(i)}","post":"function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if('object'==typeof g)for(h in g)i[h]=g[h];i.url=f}else if('object'==typeof f)for(h in f)i[h]=f[h];return i.type=i.type||d,i.oauthio={provider:a,tokens:b,request:c},e.http(i)}"}

As you can see, there are functions nested as values. My objective is to reconstruct this JavaScript object without the quotes around the functions, as they are being treated as strings. The desired format is:{key : value}

Currently, the output looks like this:{key : "value"}

Answer №1

QUICK ANSWER:

Here is a function that can achieve the desired outcome:

function fixObject(obj){

    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            obj[prop] = eval("(" + obj[prop] + ")");
        }
    }

}

If your JSON parsed object is named obj, simply call the function like this:

fixObject(obj);
console.log(obj); // this will show the changes in the console

EXPLANATION (IF YOU NEED ONE):

By enclosing the string in parentheses before using eval, you can obtain the javascript function expression.

The steps to achieve this are:

  1. Enclose the function expression string in parentheses
  2. Evaluate the function declaration expression using eval
  3. Assign the function declaration expression to the same property initially containing the string value

For the example provided, you can proceed as follows:

var obj = {
  "get": "function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if('object'==typeof g)for(h in g)i[h]=g[h];i.url=f}else if('object'==typeof f)for(h in f)i[h]=f[h];return i.type=i.type||d,i.oauthio={provider:a,tokens:b,request:c},e.http(i)}",
  "post": "function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if('object'==typeof g)for(h in g)i[h]=g[h];i.url=f}else if('object'==typeof f)for(h in f)i[h]=f[h];return i.type=i.type||d,i.oauthio={provider:a,tokens:b,request:c},e.http(i)}"
};

obj.get = eval("(" + obj.get + ")");
obj.post = eval("(" + obj.post + ")");

You can automate the process with this function:

function fixObject(obj){

    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            obj[prop] = eval("(" + obj[prop] + ")");
        }
    }

}

Your final code should look something like this:

function fixObject(obj){

        for (var prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                obj[prop] = eval("(" + obj[prop] + ")");
            }
        }

    }


var obj = {
  "get": "function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if('object'==typeof g)for(h in g)i[h]=g

    [h];i.url=f}else if('object'==typeof f)for(h in f)i[h]=f[h];return i.type=i.type||d,i.oauthio=

    {provider:a,tokens:b,request:c},e.http(i)}",
  "post": "function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if

    ('object'==typeof g)for(h in g)i[h]=g[h];i.url=f}else if('object'==typeof f)for(h in f)i[h]=f[h];return i.type=i.type||

    d,i.oauthio={provider:a,tokens:b,request:c},e.http(i)}"
};

fixObject(obj);

Footnotes:

If you are curious about the need for parentheses in eval, you can read more about it here.

Answer №2

Instead of relying on eval, consider this alternative approach:

Assuming that the variable obj contains your JSON data and the function is represented as obj.get, but in string form. To convert it into an actual function, you can utilize the Function constructor.

obj.get = new Function(obj.get);

Keep in mind that I tested this method with your code, however, the string you provided contains some errors. Make sure that your function is accurately represented.

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

Obtain the chosen option from an HTML select element by utilizing JavaScript

This is my HTML snippet: <div id="detail"> <div class="d_left"> Page <strong>1</strong> of 107 </div> <div class="d_center"> <table> <tr> <td><a href="#">Previous&l ...

How about starting a Node.js application with specific configurations?

Is there a way to develop a Node.js app that can be initiated with additional parameters? Here are a few examples: node myApp.js -nolog This command would initialize the app with the custom parameter noLog=true, preventing console logging. node myApp.js ...

Unusual shadow cast by the box's silhouette

I am currently facing an issue with a box and its shadow. When I close the box, a different shadow lingers behind. I have tried troubleshooting this problem but cannot pinpoint the source. I have included the relevant code files in the specified folders. I ...

Variable for Sweet Alert Input Box

I am completely new to PHP and JavaScript, so my question is fairly straightforward... I have a JavaScript code snippet (Sweetalert2 text field) and I'm looking to capture the information entered by users in a separate PHP file using AJAX. I've b ...

Issue with handling .bind in Angular's karma/jasmine tests Angular's karma/j

When writing unit tests for my functions, I encountered an issue with a bound function in the test runner. The problem arose when trying to bind a function to have reference to 'this' inside an inner function. Here is the code snippet in question ...

Error encountered with Protractor: 'TypeError: undefined is not a function'

I have explored various discussions on this particular error code. Nevertheless, I am finding it challenging to come across any solutions that are effective (or perhaps I am just not understanding them). While constructing a Protractor test for a webpage, ...

I aim to utilize a minimal number of variables that have been extracted using a JSON extractor in JMeter, and apply them in

Extracting data from an API in Jmeter can be quite complex, especially when dealing with multiple variables. In this particular case, we have extracted two variables using a JSON extractor. The first variable, named "name," contains data such as {abc,asd, ...

What is the best method for extracting a specific value from this JSON data?

Trying to extract the text value from a JSON response? Wondering how to retrieve the 'text' field, specifically looking for "Киргизия, Бишкек, Чуйский проспект, 213" ?? { "response":{ "GeoObjectCollection" ...

Guide to displaying options in the Vue material select box even when the default value is blank

I have implemented the material design framework vuematerial with vue.js. In traditional HTML, a selection box looks like this: <select> <option value="">You should initially see this</option> <option value="1">One</o ...

Trouble with second function invocation in JavaScript

After creating two sets of arrays and passing them into different functions, I noticed some strange behavior. The first time I called the functions for scores1, everything worked perfectly. Likewise, the second time I called the first function (for Scores2 ...

Comparison Between MySQL and JSON - Which is the Better Choice?

I'm in the process of developing a new web application or game. When it comes to storing information, would it be more efficient to use MySQL tables or json files? Both options can hold data and can be processed using PHP. What are the benefits and dr ...

A Guide to Effectively Extracting Data from Second Level JSON Arrays with

Hi, I'm having difficulty fetching the two attributes under CategoryImage in the second level of the JSON array parsing. Can someone help me with this? Thank you. <script> $(document).ready(function() { var cat=""; ...

Why is it that injecting javascript within innerHTML seems to work in this case?

According to the discussion on this thread, it is generally believed that injecting javascript in innerHTML is not supposed to function as expected. However, there are instances where this unconventional method seems to work: <BR> Below is an examp ...

`Error encountered when attempting to convert date with Angular JS filter`

Utilizing angular js filter in the controller for date formatting. A user selects a date from a uib-datepicker-popup. The goal is to format this date using ISO 8601 (yyyy-mm-dd) date format. Upon logging the user-selected date, the output is as follows: S ...

Tips for swapping out a new line character in JavaScript

Hello! I'm currently facing a challenge with some code. I have a function designed to replace specific HTML character values, such as tabs or new lines. However, it's not functioning as expected. var replaceHTMLCharacters = function(text){ tex ...

"Is it possible to draw on top of a canvas element that's already been

I'm currently working with an OpenLayers map that includes WMS layers with time steps. My goal is to create a loop that updates the time for each step and then saves the image once it's rendered. I've been referencing the example code from t ...

What is the best way to set a boolean value for a checkbox in a React project with Typescript?

Currently, I am working on a project involving a to-do list and I am facing an issue with assigning a boolean value to my checkbox. After array mapping my to-dos, the checkbox object displays 'on' when it is unchecked and a 'Synthetic Base E ...

Utilize API to extract data from JSON files and generate a database entry

Looking to create a database using a JSON file, specifically this one: JSON file Utilizing Visual Studio 2015 and MSSQL 2012. I am incorporating options like Entity Framework with MVC and WEB API template. While I want to use LINQ, I'm unsure of the ...

Utilizing Vue.js: accessing a global value within a template string

I am working on a simple Vue.js application with the following structure: index.html (only the <body> for brevity) <div id="root"></div> main.js var settings = { title: 'My App', } new Vue({ el: '#root', tem ...

Should I serialize a 2D array in JSON format and send it as two separate arrays, or is

When it comes to sending a 2-dimensional array (along with several other variables) to PHP using jQuery.ajax(), I have a couple of options in mind: One option is to serialize to json using JSON-js Another option would be to send both arrays as csv string ...