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

How to incorporate both images and text in a UIPickerView using Swift?

Can anyone provide an example showcasing how to integrate a UIPickerView in swift, including the display of both images and text using JSON for data loading? ...

How can one transform a web-based application into a seamless full-screen desktop experience on a Mac?

"Which software can be utilized to enable a web application to display an icon on the desktop of a Mac computer, while also opening up the web application in a fully immersive full-screen mode that supports all the touch and gesture functionalities provi ...

Managing stream pauses and resumes in Node.js using setTimeout()

After some experimentation with Node.js (v4.4.7), I managed to create a simple program to play a sound... const Speaker = require('audio-speaker/stream'); const Generator = require('audio-generator/stream'); const speaker = new Speake ...

Iterating through a JSON object to verify the presence of a specific value

I have a JSON Object and I am looking for a way in Angular 6 to search for the value "Tennis" in the key "name". Can you provide guidance on how to achieve this? { "id":2, "name":"Sports", "url":"/sports" "children":[ { "id":1, ...

The @Input() property within an Angular component is producing an empty array as its result

I have a calendar component that has a data property marked as @Input(): import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-calendar', templateUrl: './calendar.comp ...

Mobile devices do not support HTML5 Video playback

Here is the HTML5 Video code I am using: <div id="lightBox1" class="lightBox"> <video id="video" controls preload="metadata"> <source width="100%" height="470" src="/ImageworkzAsia/video/iworkzvid.mp4" type="video/mp4"> ...

What is the process of decoding a URL in JavaScript?

Is there a better method to decode this URL in order to use it with JavaScript? URL: https://www.example.com/post.php?v=1&text=it's-me&20hello%0Aworld%0A At present, any occurrence of ' in the URL is causing an error and blank lines ar ...

Disable the scroll bar on a bootstrap modal

<span class="education"style="font-size:170%;line-height:150%;">&nbsp;Education <br> <small style=" color:gray;font-size:60%;">&nbsp; Blue Ridge University,2012-2014 </small> <br> <sma ...

"Modify hyperlink attributes to enhance security and optimize user experience

$("a[href*='youtube']").attr('rel', 'prettyPhoto'); Having some trouble targeting links on a page containing "youtube" in the URL. I'm trying to set their rel attribute to "prettyPhoto" so they open in a lightbox window. ...

Recording Audio Using ReactJS

I am exploring ways to record audio using ReactJS and save it on my Node server. Initially, I attempted to utilize the "react-audio-recorder" module but encountered issues when attempting to record multiple audios consecutively. Additionally, I experiment ...

My function invocations seem to be malfunctioning

Originally, I wrote code without using functions to prototype and it worked perfectly fine: $(function() { $(".PortfolioFade img") .mouseover(function() { popup('PORTFOLIO'); var src = $(this).attr("src").rep ...

The process of implementing web-based online diagramming software involves a strategic approach to designing and integrating various

I'm really interested in learning how web-based online diagramming software works. If anyone could provide guidance or point me to example resources, I would greatly appreciate it. Here are some of the web-based online tools that I have been explorin ...

The deep reactivity feature in Vue3 is functioning well, however, an error is being

I am currently using the composition API to fetch data from Firestore. While the render view is working fine, I am encountering some errors in the console and facing issues with Vue Router functionality. This might be due to deep reactivity in Vue. Here is ...

The "smiley" character added to the information during an Ajax call

Encountering an unusual issue. A colon (:) character is being appended to the JSON data sent to the server via AJAX request. https://example.com/image1.png The colon character seems to appear after sending the JSON, but it does not show up when inspectin ...

Using Vue.js to invoke an external JavaScript function for search functionality

In my vue.js application, I have a list of users with backend pagination. Now I want to implement a search functionality. I attempted to call the method like this: watch: { search: function() { Crud.methods.getItems(); } }, Howe ...

Tips for retrieving data from an Excel spreadsheet on an HTML/CSS webpage

I have a single HTML template at this location: . The current page is tailored for the state of Arkansas in the US, but I now need to replicate the design for all 50 states. Each state page will have the same layout, but different content specific to that ...

Basic jQuery request for JSON data

In an effort to send user data to a PHP script and display the results in an element, I am utilizing JSON. The process works smoothly until reaching the response stage. Despite receiving the correct results when logging to the console, attempting to append ...

Is it necessary to have both index.js and Component.js files for a single component in React?

Continuously analyzing various projects, I often come across authors who organize their file structures in ways that are perplexing to me without proper explanation. Take, for instance, a component where there is a folder named Header. Inside this folder, ...

Refreshing Child's Activities

In my scenario, I am displaying data in a child action and utilizing buttons to modify the displayed information. Here is an example of how I am achieving this: Index.cshtml <head> <script type="text/javascript"> $("#RefreshView").on ...

Can Vue recognize array changes using the Spread syntax?

According to Vue documentation: Vue is unable to detect certain changes made to an array, such as: Directly setting an item using the index, for example vm.items[indexOfItem] = newValue Modifying the length of the array, like vm.items.length = newLength ...