Transform a JSON object string into a usable value

I'm currently working on a function that takes a string, splits it, and then formats it using json[key][key2][key3]. The issue is that 'n' could potentially be infinite (not literally but needs to be written as such)

function getJsonValue(json,string) {
    var vals = string.split(".");
    var x = vals.length;
    var newString = '';
    while (x != 0) {
      newString += "['"+vals[(vals.length-x)]+"']"
        x--
    }
    return newString;
}

For example, this will produce:

"['condition']['item']['condition']['temp']"

I need to retrieve a value from that by combining it with a json object, like

json"['condition']['item']['condition']['temp']"

However, I am unsure if this is possible or how to achieve it.

Edit: The challenge I am facing is that I need any value from a config file to be passed in and then parsed by a returning function. For instance, a user knows the value will be condition.item.condition.temp for a specific query. I am attempting to create a single function that can handle all scenarios and pass in configuration values for the expected output. Therefore, in one query, the desired value might be condition.item.condition.temp and in another, it might be condition.wind.chill.

Answer №1

It seems there might be some confusion in understanding your task, but if you are dealing with a JavaScript object named json and a string formatted as field1.field2.field3, and your goal is to retrieve the value of json.field1.field2.field3, here's a possible solution:

function fetchValueFromJson(json, string) {
    var keys = string.split(".");
    for (var i = 0; i < keys.length; i++) json = json[keys[i]];
    return json;
}

You can apply this function on an object like this:

var data = { field1: { field2: { field3: "Hey there!" } } };
var result = fetchValueFromJson(data, "field1.field2.field3"); 
console.log(result); // outputs Hey there

Answer №2

Check out the lodash documentation for using the get method.

_.get(data, 'property1.property2.property3')

By constructing the "path" in your code, you can utilize lodash to extract the desired value efficiently.

Answer №3

Have you considered using the eval function?

let data = {
    'first': {
        'second': {
            'third': {
                'fourth': 4
            }
        }
    }
};

alert(eval("data['first']['second']['third']['fourth']"))

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

Strange results appearing on my node.js server - removing object

When I run node.js in the terminal, I get this output: node server.js { hand: [ [ [Object], [Object] ], [ [Object], [Object] ], [ [Object], [Object] ], [ [Object], [Object] ] ], deck: [ { suit: 'c', rank: 'a' ...

Encountering a peculiar problem with the Bootstrap Carousel where the first slide fails to load

There seems to be an issue with the bootstrap carousel where the first slide appears empty initially, but once you slide to the second slide it starts working fine. Navigating through all slides is still possible. <div id="mediakit_carousel" class="car ...

How can I retrieve the identical fingerprint used by AWS from x.509 using node-forge?

Is there a way to obtain the certificate ID / fingerprint of an x.509 certificate using the node-forge library? Update I am trying to configure AWS IoT and believe that AWS uses a specific fingerprint algorithm to generate the certificate ID. This inform ...

Is there a method to display a loading animation while the micro apps are being loaded in a single spa project?

Currently, I am working on a project using single spa and I need to implement a loader while my micro app is being loaded. Additionally, I also need the loader to be displayed when switching between these micro apps. Are there any methods to accomplish t ...

BOOTSTRAP: changing the layout of panels in various sizes for mobile devices

I'm struggling with how to reorganize my panels on mobile devices. Each panel has a different size. Please refer to the attached screenshot for the page layout on large screens (col-lg): https://i.sstatic.net/xcqaT.png EDIT: The layout on large scre ...

Discovering the flaw in my programming that pertains to JSON parsing

After countless hours of searching and reviewing documentation, I am still unable to identify the issue with my jQuery code. My goal is to practice reading a local JSON file and displaying its contents in the body of my HTML document. $(document).ready(fu ...

Connecting Next.js to a Database: A Step-by-Step Guide

I am interested in developing an application similar to Samsung Health that will involve heavy querying on a database. I am unsure whether it would be more beneficial to create a custom server using Node.js (with Express.js) instead of using the integrate ...

Tips for transferring data to the next page with JavaScript AJAX

I am working on a webpage that includes an html select element <pre> $query = mysql_query("select * from results"); echo "<select id='date' onchange='showdata()' class='form-control'>"; while ($arr = mysql_fetch_a ...

How shouldjs makes value verification effortless for unordered arrays

In my express.js application, I'm currently using supertest and should.js as my preferred testing framework. However, I've encountered some difficulties when it comes to testing for specific values within an unordered array. After referring to t ...

Best practices for declaring variables in ReactJS

I need help understanding how to declare a variable in a React JS class so that it is accessible in different functions. Here is my code snippet: class MyContainer extends Component { constructor(props) { super(props); this.testVariable ...

difficulty with parsing JSON in jQuery when referencing an external file containing the same data

Looking for help with parsing a json file using jquery? Check out this working sample: http://jsfiddle.net/bw85zeea/ I'm encountering an issue when trying to load "data2" from an external file. The browser keeps complaining that it's an invalid ...

Which function is triggered first - onclick or ng-click?

Currently, I have a button with a validation process occurring on click. The validation process triggers a web service call and other processes if successful. However, I'm uncertain if the validation is actually taking place. This is my page setup: ...

When the user clicks on an organizational chart, a new organizational chart will appear in a modal popup

Currently, I am developing a project with Highcharts where I have a specific requirement to display a modal popup when a node on an org chart is clicked. The popup should also contain another org chart. Below is the code snippet I am working with: [link to ...

Can you explain the purpose of `import type {Node} from 'react';` and how it is used in the App component as: () => Node?

Executing the following command: npx react-native init AwesomeProject When reviewing the App.js file, I came across two lines that confuse me: import React from 'react'; import type {Node} from 'react'; // Line 1 import { SafeAreaVi ...

Execute JavaScript function after completion of CSS animation using jQuery

I'm working on an accordion feature that uses CSS animation to expand the clicked item. The expansion is triggered by li:target. However, I'm facing an issue where when clicking on an item, the scroll position doesn't align correctly with t ...

reveal a hidden div by sliding it during an onclick action

My PHP while loop code is as follows: while (...($...)){ $convid = $row['ID']; echo" <button onclick='getconvo($convid)'>open</button> <div class="convowrap"></div> "; } Here is the correspond ...

Creating a nested JSON file dynamically in Angular: A step-by-step guide

I am looking to dynamically generate a nested JSON file within an Angular project. The data will be extracted from another JSON file, with two nested loops used to read the information. Below is an example of the initial JSON file structure: { "data": [ ...

How is it possible to encounter a missing semicolon CssSyntaxError during a Gatsby build?

Currently, I am in the process of developing a Gatsby page with Material UI. The design of the page is almost finalized; however, upon completing the project, an unexpected build error occurs when running npm run build. WebpackError: Pathname: /invitation/ ...

Can Java provide functionality similar to JS callbacks?

Can a similar functionality be achieved in Java? function sum(num1, num2, onComplete) { var result = num1 + num2; onComplete(result); } (function(){ sum(3, 5, function(res){alert(res)}); })() Is it possible to implement this in Java without ...

Launching the forEach function within an ng-repeat loop was it can be done by

I need to implement a function within the ng-repeat that will convert the value of Qprogress object in my JSON into a percentage. I already have the function written, but I am struggling with how to trigger it. I attempted to use a forEach loop inside the ...