How can I extract the JSON value as a string?

I have a scenario where I define two objects. The first object, BOB, has properties "name" with a value of "bob" and "height" with a value of 185.

var BOB = {
 "name": "bob",
 "height": 185
};

The second object, PROPS, references the height property from the BOB object.

var PROPS = {
"bob": {
  "height": BOB.height
};

As a result, PROPS.bob.height will be equal to 185. When stringified, the object looks like this:

{"bob": {"height": 185}}

Now, the challenge is to determine the original source code that evaluated to the value 185. Is it possible to extract the string representation of the code that produced that result?

var s = findOutTheSourceCode(PROPS);

// The expected output for s would be
/*
{
"bob": {
  "height": BOB.height
}
*/

Answer №1

Typically, no. That data is not usually kept in storage.


However, if the code was integrated into a function and you possess a link to that function and you are utilizing a JS engine with support for this atypical feature, it may be possible to call thatfunction.toString() and then attempt to locate the relevant section of code through methods like pattern matching.

Answer №2

This design lacks elegance and practicality.

To answer your question directly, the simple answer is "NO, it's not possible."

However, there is a solution that some may consider unattractive but involves using eval, which is generally discouraged. Here is an example:

var BOB = {
 "name": "bob",
 "height": 185
};

var PROPS_src = '{\n'
    + '  "bob": {\n'
    + '    "height": BOB.height\n'
    + '  }'
    + '}';

eval('var PROPS = '+PROPS_src);

console.log("PROPS_SRC:__________________");
console.log(PROPS_src);
console.log("PROPS:______________________");
console.log(PROPS);

// Output:
// PROPS_SRC:__________________
// {
//   "bob": {
//     "height": BOB.height
//   }}
// PROPS:______________________
// { bob: { height: 185 } }

However, I must stress that this approach is highly discouraged. It is strongly advised to reconsider your data structures and possibly refactor your code to improve traceability of data sources.

Here's a (quick and dirty) alternative:

var people = {
    bob: {
     "name": "bob",
     "height": 185
    }
};

var props = {
  "bob": {
    "someConstant": "Hello World",
    "_height": "height",
  }
};

function getProps(who){
    var out = {};
    Object.keys(props[who]).map(function(k){
        if (k.substring(0,1) == "_") {
            out[k.substring(1)] = people[who][props[who][k]];
        } else {
            out[k] = props[who][k];
        };
    }); 
    return out;
};

console.log("Raw:", props['bob']);
console.log("Calculated:", getProps('bob'));

// Output:
// Raw: { someConstant: 'Hello World', _height: 'height' }
// Calculated: { someConstant: 'Hello World', height: 185 }

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

Encountering a CSS problem while attempting to design a section featuring a background image

On this page, I have the login bar on the right and the footer at the bottom. I want a div to sit in the area currently occupied by the background image and fill it with the full background image. Currently, everything is wrapped in a wrapper and the back ...

Ways to retrieve an array following a function call

After a lot of testing and troubleshooting, I finally got my array to function properly in the console. However, when I click the button, the array is displayed on the console but not in my HTML. TS: jogar(){ for(var u=0;u<6;u++){ this.y ...

Setting up the current user's location when loading a map with Angular-google-maps

I am currently utilizing the library in conjunction with the IONIC framework. To manually set the center of the map, I have implemented the following code snippet: .controller('mainCtrl', function($scope) { $scope.map = { cen ...

Issue with displaying Images on Datatables using Javascript

I have been scouring the depths of the Internet. Everything was running smoothly, I was handling image uploads and retrievals with NodeJs to MongoDB using the schema below: image: { data: fs.readFileSync(path.join(__dirname, '/public/uploads/&apos ...

Activate when every single pixel within an element is see-through

I've designed a web page that includes two canvas elements stacked on top of each other. The purpose of this setup is to allow me to "erase" the top canvas and reveal an image loaded into the bottom canvas. So far, this functionality has been working ...

Styling is applied by Bootstrap to inputs in a form that are not required

I am currently working on validating a form for empty fields using Bootstrap. When submitting and validating the form with the form.checkValidity() method, I noticed that even the non-required fields are being styled as if they are required. Is this normal ...

What is the best way to send a prop to my home route following a redirect?

I am working with react-router-dom and I want to pass :id to my first route (/) when redirecting. This is important so that I can access :id in my Interface component and maintain consistent URL structure for my single-page application. Is it feasible to a ...

What is the reason behind the linking or appearance together of src/pages in Visual Studio Code?

As I venture into the world of Visual Studio Code (VSC) and follow a Gatsby tutorial, I've noticed that every time I create a new directory, VSC seems to automatically link src/pages together. However, my preference is for pages to be a subfolder of s ...

Is it possible to create a DOM element with a click handler all in one step?

I am looking to dynamically create an element, like this: var productItemTop = $( "<span>" + "<a class='spamItemsX' href='#' " + "onclick=" + eval(launchGenericProductSearch(topProducts)) ...

Updating a React event as it changes with each onChange event

Let's address a disclaimer before diving into the issue - for a quick look, visit this pen and type something there. The Scenario This is the JSX code snippet used in my render method: <input value={this.state.value} onChange={this.handleCh ...

Switching from Gson to Jackson, I'm grappling with the complexities of generics and creating custom deserializers

We are currently exploring the use of Jackson as an alternative to Gson, but I am facing difficulties grasping the concept of generics. It seems like a straightforward issue that I just can't seem to find the answer to, despite searching through Googl ...

Steps to retrieve an array from AJAX request and save it to a JavaScript variable

How can I retrieve the 'this.responseText' array from this function and assign it to a variable named 'teacherIDList'? Any suggestions? var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readySt ...

How to Extract Specific Data from JSON Response using Jquery?

How do I extract specific fields from this Json Result or response with the following structure? var WPQ3ListData = { "Row" : [{ "ID": "27", "PermMask": "0x400001f07fff1bff", "FSObjType": "0", "Title": "NOOO", "FileLeafRef": "27_.000", "Total ...

Selection List dictates the necessity of JavaScript

I need to create a JavaScript code that will require the comment field (textarea) when a selection is made from a list. Currently, I have added a required icon next to the comment section but I am stuck at this point. See the code below. Thank you in adva ...

Ways to access a particular property of a child component object from the parent component

Is there a way to access a child component's "meta" property from the parent component without using the emit method? I am aware of the solution involving an emit method, but I'm curious if there is a simpler approach to achieving this. // Defau ...

The offcanvas close button fails to function if initialized through JavaScript

I have integrated offcanvas into the page layout. By default, it remains hidden but I want it to be visible at all times on large screens. On smaller screens, there should be a button to dismiss it, as well as another button in the menu panel to show the o ...

Navigating a list using AngularJS within an HTML view: tips and tricks!

Implementing AngularJS within the context of the Ionic framework. The $scope on the front-end consists of: an object User that contains a list of sports: $scope.user = { sports: { "running": true, "football": true } } a list named "matches" containing u ...

Tips for showing/hiding textboxes based on select options:

I am currently working on a project that allows users to enter their personal information. I need help figuring out how to show or hide textboxes based on the selection made in a dropdown menu. The dropdown menu in question is for marital status. The opt ...

jQuery loops through form fields and sets them as disabled

Trying to solve a question... In a form with multiple inputs, I only need to loop through the ones inside the div tagged player. <div class="player"> <input type="text" value="0" class="unit" /> <input type="text" value="0" class="unit" ...

Modify a boolean value within a JSON file using jq

I need to modify a boolean value in a json file using jq. This is how my json file looks: { "kind": "KubeletConfiguration", "apiVersion": "kubelet.config.k8s.io/v1beta1", "address": "0.0.0.0&quo ...