Turning a JSON dot string into an object reference in JavaScript: A simple guide

Having a JSON object labeled test with values like this: {"items":[{"name":"test"}]}, I need a way to apply the string items[0].name to it in order to search for a specific value (test.items[0].name). Currently, my only idea is to create a function that parses square brackets and dots. Is there an alternative method, possibly involving eval (though I prefer to avoid it)?

To clarify, I have a JSON object where the details are not important. What matters is being able to query the object using a string, such as theobject.items[0]. The challenge lies in the fact that the query string (e.g., items[0]) is unknown - consider it user input stored as a string (var thisIsAString = "items[0]"). So, I require a way to append this query string to theobject in order to retrieve the value at theobject.items[0].

Answer №1

function findValue(object, pathName) {

  pathName = pathName.split('.');
  var arrayPattern = /(.+)\[(\d+)\]/;
  for (var index = 0; index < pathName.length; index++) {
    var matchArray = arrayPattern.exec(pathName[index]);
    if (matchArray) {
      object = object[matchArray[1]][parseInt(matchArray[2])];
    } else {
      object = object[pathName[index]];
    }
  }

  return object;
}

var attribute = findValue(dataObject, 'products[0].price');

Answer №2

...When working with JSON data, it's important to differentiate between strings and objects. If you can access the data using dot/bracket notation, then it's a JavaScript object/array...

If you are handling a pure string like this:

'{"name":"string","array":[0,1,2]}'

You will need to use JSON.parse on it;

var json_string = '{"name":"string","array":[0,1,2]}',
    js_obj = JSON.parse(json_string);

js_obj.name; // "string"
js_obj.array; // [0,1,2]
js_obj.array[1]; // 1

If the data is not just a string but an object/array with nested objects/arrays, you can simply do:

myObj.items[0].name = items[0].name;

If it turns out to be a string, parse it with .parse and carry out the same operations as demonstrated above. And if you need to convert it back to a string for server transmission, utilize JSON.stringify like so:

var json_string = JSON.stringify(js_obj);

Your modified JSON string is now ready.

In case you require compatibility with older versions of Internet Explorer (such as IE < 8), consider downloading json2.js by Douglas Crockford and conditionally adding it to your page if window.JSON is unavailable.

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 designing a search bar using Angular

search : ____________ I am interested in designing a search bar functionality that automatically triggers when the user inputs 8 or more characters. The input text will be stored in a variable, the search bar will be reset, and the backend API will be che ...

Retrieve the current URL of an IFRAME

How can I easily retrieve the current URL from an embedded iframe? The user will be navigating through various web pages. I assume that some JavaScript code would be needed for this task. ...

Managing numerous range sliders in a Django form

My Request: I am looking to have multiple Range sliders (the number will change based on user selections) on a single page. When the sliders are moved, I want the value to be updated and displayed in a span element, as well as updating the model. The Issu ...

The Array map function is not displaying the list within a React component that is based on a Class

I am having trouble displaying a list of food items in my Parent component FoodBox.js and its child component FoodItems.js. I am using the map() method, but the <ul> element is showing up empty. Here is my code for FoodBox.js const FOOD_ITEMS = [ { ...

Load a script in a specific div using React

Can anyone assist me with loading a script onto a specific component in my React application? Here is the script that needs to be loaded at the bottom-most div within my component: <div id="rexxxx"></div> <script> new carouselI ...

Implement a Loop that Generates Buttons with Popups Using jQuery Mobile

Within the context of XML parsing, I have utilized this code to generate buttons dynamically using a loop: $('#button' + counter + paramcounter).click(function(){ sendData(escape(parameterarray[cnt2] + $('#textinput' + cnt + cnt2).v ...

Having trouble parsing JSON elements separately

I am currently working on generating data to be utilized in a chart.js plot by utilizing C# Controller and javascript. The Controller method I have returns a JSONResult to a javascript function. public JsonResult GetPlansPerDoc(){ //Code to retrieve d ...

Mandrill: Issue with merge_vars functionality

I am trying to send different links to user emails through Mandrill 'merge_vars' feature, but I am encountering an issue. Here are the relevant excerpts from the API log: "message": { "preserve_recipients": false, "auto_text": false, ...

Creating PHP functions that return a JSON string when invoked - a simple guide

I have created a script that contains various functionalities, including fetching data from a database and encoding it into JSON. However, I want to be able to call different functions to execute these scripts separately. When I attempted to define and c ...

Dynamic Form Submission - Displaying Notifications for Success and Failure

While I have managed to successfully submit my form using PHP, I am currently facing some challenges with AJAX. Whenever I submit the form, an error message pops up as if 'res' is false instead of true. Despite my efforts to troubleshoot and rese ...

Struggling to grasp the concept of PHP LZW decompression function within JSend framework

I am currently working on converting the LZW decompressor from PHP to JavaScript and I have encountered a function that is giving me some trouble. function decompressLZW(aCodes) { var sData = ''; var oDictionary = []; for (var i = 0; i &l ...

Issue with triggering ReactJS onClick function accurately

For the function to work correctly, I had to add e.preventDefault(). However, my goal is for it to redirect the user to '/' after submitting the form. Below is the function that I am attempting to trigger: onAddPoints = (e) => { e.prevent ...

Is it possible to override values set in the constructor(props) in React? If not, what is the best way to set defaults that can be overwritten later?

I'm confident I know the solution to this problem because my setState({}) seems to have no effect. This is the constructor code that I currently have: constructor(props) { super(props); this.state = { percentiles: { incN ...

Begin a SeleniumWebDriver session after Google Chrome has been launched beforehand

I am looking to create an automation using SeleniumWebDriver and Node.js, but I am facing an issue where I cannot start the automation if Google Chrome is already open and in use by the user. Currently, my workaround is to close all instances of Chrome be ...

Unable to display toast notification in React/MUI/Typescript project

Currently tackling error notifications targeted at 400,401, and 500 errors within a large-scale project. I am facing an issue where I want to integrate my ErrorToastNotification component into my layout.tsx file to avoid duplicating it across multiple page ...

Handling Slow Json Response in C# with MVVM Pattern

I'm encountering an issue where a function I want to load in the constructor for making a webservice request is not displaying properly. Let's start by looking at the working code (without the request). ViewModel - before request public Fri ...

Unable to execute PHP alongside a JavaScript event listener

Using PHP, I am creating a canvas for writing and the text output will appear in a textarea (handled by other functions). There are additional input tags like a title to gather user input. The values from these input tags (title and textarea) will be submi ...

"Encountered a 'NextAuth expression cannot be called' error

Recently, I delved into learning about authentication in Next.js using next-auth. Following the documentation diligently, I ended up with my app/api/auth/[...nextauth]/route.ts code snippet below: import NextAuth, { type NextAuthOptions } from "next-a ...

What is the best way to resize a div located below a dynamic div in order to occupy the available space?

My website has a dynamic div1 and a scrollable table inside div2. I need the div2 to take up the remaining height of the window, while ensuring all divs remain responsive. I've tried using JavaScript to calculate and adjust the heights on window loa ...

Navigating through and extracting data from an object in JavaScript

Given the function call destroyer([1, 2, 3, 1, 2, 3], 2, 3);, I am trying to retrieve the last 2, 3 part after the initial array. However, I am unsure about how to achieve this. When I use return arr[6]; or return arr[1][0], both statements do not return ...