Locating the JSON path within an object

Need help with checking if a specific path is present in a JSON object?

var data = {
  "schemaOne": {
    "name": "abc",
    "Path": "i.abc",
    "count": 5347,
    "subFolders": [

    ]
  },
  "schemaTwo": {
    "name": "cde",
    "Path": "i.cde",
    "count": 0,
    "subFolders": [
      {
        "name": "efg",
        "Path": "",
        "count": 0,
        "subFolders": [

        ]
      },
      {
        "name": "hij",
        "Path": "i.hij",
        "count": 1,
        "subFolders": [

        ]
      }
    ]
  }
}

var inputpath = "data.count";

I have found this code after researching that checks for the path o.Path but I need to modify it to dynamically check if the path data.count exists in the JSON object.

function updateData(obj, path, count) {
  if (obj.Path == path) {
    obj.count = count;
  } else {
    var array;
    if (Array.isArray(obj)) array = obj;
    else if (obj.subFolders) array = obj.subFolders;
    else return;
    for(var i=0; i < array.length; i++) {
      updateData(array[i], path, count);
    }
  }
}

Answer №1

It seems like the question provided lacks clarity in terms of its use case. As mentioned before, obj is a JavaScript object and not in the JSON format.

If I interpret correctly, you are looking to verify if a specific path, represented as a string (e.g. "obj.count"), exists within that object.

An expedient but risky approach (since using eval is discouraged due to potential security risks) could be:

if(eval(inputpath)){
    //... perform certain actions
}

Alternatively, I recommend creating a function that takes an object and a string (the path) as arguments, parses the string path, and verifies if the object includes that path.

You can start by referring to this resource: Accessing nested JavaScript objects with string key

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 a JSON data structure within the Swift Socket.IO Client

How do I go about receiving a JSON object within the Swift Socket.IO client? Node.js When using socket.io on Node.js, I emit a JSON object like in this simple example: socket.emit('welcome', { text : 'Hello, World!' }); Swift In an ...

Retrieving data from a C# datatable in JSON format and presenting it in a jQuery datatable

Recently, I've been diving into Jquery Datatable and trying to work with it using a JSON string. However, despite my efforts over the past couple of days, I haven't been able to get the desired output. Here's a snippet of my HTML : <bo ...

What is the process for transferring a document from one database to another in couchDB?

Is it necessary to load a couchDB JSON document to the client first and then post it to another couchdb database in order to copy it from one db to another? Or is there a server-side method that can achieve this? Reference The copy command is non-standar ...

Retrieving input values with JQuery

HTML <td data-title="Quantity"> <div class="clearfix quantity r_corners d_inline_middle f_size_medium color_dark m_bottom_10"> <button class="btn-minus bg_tr d_block f_left" data-item-price="8000.0" data-direction= ...

Mastering the control of a camera in three.js using a combination of keyboard and mouse navigation techniques

I have been working on a 3D environment in WEB GL using three.js, previously using orbitcontrols.js as shown in this project: http://codepen.io/nireno/pen/cAoGI. Recently, I came across a different method of navigating the environment using the W, A, S, D ...

What is the best way to implement a fadeout or timeout for success and warning alerts in OpenCart 2.2?

Is there a way to set a timeout for alert boxes in Opencart 2.2 so that they disappear after a few seconds? I've tried the code below, but it didn't work out. Alternatively, is it possible to make the popup disappear when clicking anywhere on the ...

Transforming a JavaScript Date object to a Java LocalDateTime

In my current project, I am facing a challenge while attempting to pass UTC time from a JavaScript front end to a Java backend. My initial approach involved utilizing the Date.toISOString() method and sending the generated object to the Java backend. Howev ...

Disabling an HTML attribute on a button prevents the ability to click on it

In my React application, I have a button component that looks like this: <button onClick={() =>alert('hi')} disabled={true}>test</button> When I removed the disabled attribute from the browser like so: <button disabled>test& ...

Filtering required on the JSON payload of the Stackdriver Alerting Policy

Within our organization, I have a Python script running under App Engine that collects data on all projects. This includes information on: Disks not associated with snapshot policies Snapshot policies that do not follow our naming convention by lacking " ...

Using Python to display JSON data

I've developed a script that retrieves JSON user details, and I'm looking for ways to display the "name": "admin". Any suggestions on how this can be achieved? Here is the script snippet: import xmlrpc.client import json clas ...

Encountered an error while trying to find the Node JavaScript view

Whenever I attempt to render the URL for displaying index.js in the browser, an error arises: **Error:** Failed to locate view "index" in views directory "D:\NodeJs\Example\5expressnodjsexmp\views" Below is my application code: //Hea ...

What is the best approach to perform a search in mongoose based on specific query parameters?

I have a form that allows users to search for transactions by specifying the buyer name, item name, or both. This means I can receive any of these queries: localhost:8000/allPayments/?i=pasta localhost:8000/allPayments/?b=Youssef localhost:8000/ ...

Enhance link with dynamic content using an AJAX call

I need help appending a picture after a link with the same URL as the link. The current AJAX code is producing the following result: <a href="images/Draadloos.png" data-lightbox="gallerij"></a> Here is an example of what I would like to achie ...

Deconstructing JavaScript scripts to incorporate HTML5/CSS3 functionality for outdated browsers such as Internet Explorer

I have been researching various resources and guides related to different scripting libraries, but none of them seem to address all the inquiries I have regarding performance and functionality. With so many scripts available, it can be overwhelming to dete ...

What is the best way to retrieve multiple variables using Express.js on Node.js?

Trying to fetch Form data from an HTML page to a Node Js server. The HTML file is named index.html <body> <nav> <ul> <li> <a href="#" class="button add">Add Product</a> <div class="dialog" style="displ ...

Determining the Percentage of a Bar Chart

When utilizing Chart.js along with the fork available at (https://github.com/leighquince/Chart.js), I successfully developed a bar chart featuring 3 bars: Goal, Actual, and Available data. My challenge lies in finding a method to calculate the percentage ...

Tips for toggling the visibility of a flexbox-styled popup using jQuery

I am trying to implement a popup on my website and I want to use flexbox styling for it. I have the necessary scss mixins for flexbox properties, however, I encountered an issue. The problem arises when I try to hide the popup using display: none, as the ...

Get numerous records from two sets of data

Scenario: I currently have two JSON files stored in my mongodb database from Yelp Educational. The first JSON is for Yelp Business and the second JSON is for Reviews. JSON1: (Yelp Business) { "business_id":"tl9XIP5trlkcuSfTQqe5jg", "full_a ...

Trigger a re-render in React using setState(null) and forceUpdate()

When using react 16, setState(null) no longer triggers an update according to the official documentation: The new behavior for calling setState with null is that it does not trigger an update. This gives you the control in the updater function to decide ...

Craving assistance in coding permutations

Thank you for responding. I want to express my gratitude for your efforts in trying to assist me. Unfortunately, I have posted this problem on multiple websites and no one has been willing to help. Regarding my code, my objective is to count permutations. ...