Exploring JSON keypaths in Javascript for advanced data manipulation

Seeking a library that can deeply parse JSON using a specified keypath to locate values within an array of dictionaries.

Take into account the JSON Object below:

{
    "root" : 
    {
        "infos" : 
        {
            "sport" : [
                        {"name" : "tennis"}, 
                        {"name" : "basket"}
                      ]
        }
    }
};

Desiring the ability to use something like

var sport = json.valueForKeyPath('root.infos.sport.name')
to obtain ["tennis", "basket"].

Attempts with underscore-keypath.min.js were unsuccessful in achieving this.

If anyone knows of a library that can achieve this, please share.

Answer №1

If you're looking for a solution, I've created a small library that can assist you in that task. You can access it on github:

https://github.com/blauharley/TemplateJS

Here's a preview of what you can achieve with this library:

var objs = [
    { dim: { x: 25, y:14, z: 3}, name: 'circle'},
    { dim: { x: 19, y:17, z: 8}, name: 'triangle'},
    { dim: { x: 7, y:44, z: 12}, name: 'quad'},
    { dim: { x: 13, y:63, z: 67}, name: 'circle'},
    { dim: { x: 5, y:23, z: -2}, name: 'rectangle'}
];
var templ = new TemplateJS();
// Separate multiple values with pipes (|)
var str = "<p>{name}: | <b style='color:green'>{dim}{x}px</b> | <b style='color:red'>{dim}{y}px</b> | <b style='color:yellow'>{dim}{z}px</b></p>";
templ.transformTemplate(objs,str);

There are two main methods available, but transformTemplate aligns with your current query. It generates an array of strings based on the provided objects. Each object's property values are inserted into the string specified in the second parameter. Ultimately, transformTemplate produces an array of transformed strings.

The second method, insertTemplate, serves a similar purpose but is mainly used for inserting multiple values into HTML elements.

By using Pipes | to separate object values and employing curly braces for placeholders, this library can handle potentially unlimited object nestings (excluding arrays), as demonstrated in the Jasmine TestCase.

However, both methods require an array of objects as the first parameter. To leverage this library effectively, consider utilizing it in the following manner:

var source = {
  'root':
  {
    'infos':
    {
      'sport': [
        {
          'name': 'tennis'
        },
        {
          'name': 'basket'
        }
      ]
    }
  }
};
var templ = new TemplateJS();
// Separate multiple values with pipes (|)
var str = '{name}';
templ.transformTemplate(source.root.infos.sport, str); // ["tennis", "basket"]

Moreover, extensive testing has been conducted across all browsers to ensure compatibility.

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

What is the best way to implement media queries for mobile phones and desktop computers?

I've come across similar questions before but still can't wrap my head around it. Here's my dilemma: I want the index page of my website to display in desktop layout on desktops and mobile jquery on mobile devices. Currently, I have set up m ...

Is it possible to retrieve JSON data from an external URL using JavaScript or jQuery?

My goal is to retrieve JSON data from the following URL: I have a button that triggers the function called "jsonplz()", which should display an alert message with the fetched JSON data. This is what my JavaScript code looks like: <script src="htt ...

Issue with JQUERY where HTML select element is not visible

$(document).ready(function(){ var selArr = [ {val: 'corsair', text: 'Corsair'}, {val: 'evga', text: 'EVGA'}, {val: 'antec', text: 'Antec'} ]; $('#pSupply& ...

Converting long date format to short date format: yyyy-mm-dd

Is there a way to convert the long date format from "Sat Dec 13 2014 06:00:00 GMT+0600" to "2014-12-13" in yyyy-mm-dd format? <script> function myDate(val) { var now = new Date("<?php echo $Cnextdue;?>"); now.setDate(now.getDate() + 30*val); ...

Illustrating SVG links

I'm working on a basic svg animation project where I want to create a simple shape by animating a line under a menu link. The goal is to have a single line consisting of a total of 7 anchors, with the middle 3 anchors (each offset by 2) moving a few p ...

Is there a way to use Regex to strip the Authorization header from the logging output

After a recent discovery, I have come to realize that we are inadvertently logging the Authorization headers in our production log drain. Here is an example of what the output looks like: {"response":{"status":"rejected",&quo ...

Cookie Cutter Chrome Extensions

Is there a way to create a cookie that can be shared between my plugin and contentPage? I've tried creating one but it doesn't seem to appear on the cookie list of the tab page. Any suggestions or ideas on how to achieve this? ...

Tips on revealing concealed information when creating a printable format of an HTML document

I need to find a way to transform an HTML table into a PDF using JavaScript or jQuery. The challenge I'm facing is that the table contains hidden rows in the HTML, and I want these hidden rows to also appear in the generated PDF. Currently, when I co ...

Tips for revealing the pin after entering it into the text box

Is there a way to display the address inputted into 4 textboxes (with pin changing after onchange) on a Google map embedded on my website? I want to have 4 separate input fields for zip code, city, street, and house number. If all four boxes are filled out ...

Uncovering the origin of a problematic included file

When using Sencha Touch, it is common to encounter issues related to missing files. In most cases, simply including the file resolves the issue. However, there are instances where the problem lies in a faulty include, requiring you to locate where the file ...

Guide to Repairing Uncaught TypeError: players.setAttribute is not a recognized method?

I'm a beginner and encountered an error saying Uncaught TypeError: players.setAttribute is not a function when submitting an action. How can I solve this issue? Please share your insights. ''' //selecting all necessary elements const s ...

The issue with AngularJS Routing is that it fails to refresh the menu items when the URL and views are being

My current project involves implementing token-based authentication using the MEAN stack. The goal of my application is to display different menu items based on whether a user is logged in or not. When there is no token present, the menu should show option ...

Tips on inserting JS code into React component

I seem to be struggling with integrating my JS code into a React component. I attempted it, but unfortunately made a mess of things. Can anyone provide guidance on how to properly accomplish this? mycomponent.js import React from "react"; import Navbar ...

Using the v-for directive to create sequential lists

I am struggling to display pairs of data from an object based on category using nested v-for loops. The object, categoryArray, contains entries such as {stage 1, red}, {stage 1, blue}, {stage 2, orange}, {stage 3, brown}, {stage 2, green. My desired displ ...

The entire component is not displayed in Vue

Just starting out with Vue. I'm looking to create a component that encompasses the entire page except for the header and footer Vue.component('main-block', {template: ` <section id="first-block">...</section> <secti ...

Node.js: Converting Hierarchical JSON into a Flattened JSON Structure

While working on a node.js script to merge all the json files in a directory and create a new json file, I encountered some issues that need to be addressed. A.json [ { "id": "addEmoticon1", "description": "Message to greet the user.", "def ...

Arranging elements on top of a fixed element using JavaScript and CSS

Currently, I am implementing Javascript code that adds a div to the body of pages. The purpose of this div is to always stay at the top of the document or window, regardless of the page's design and content. Everything was functioning correctly until ...

What is the technique for performing asynchronous querying of multiple SQL databases?

Currently, I am in the process of developing a web application using nestjs and typeorm. I have been contemplating the functionality of the following code: const r1 = await this.connection.query(sqlA) const r2 = await this.connection query(sqlB) Does th ...

Data has not been submitted to the MongoDB database

I attempted to save form data in my mongodb database (mongodb compass). However, after submitting the form, I checked the database and found that it was empty. When I clicked the sign-up button, it only displayed curly brackets. Main file - App.js co ...

"Functionality of public methods in JavaScript plugin seems to be malfunction

Recently, I made the decision to redevelop a jQuery plugin using vanilla JavaScript. However, I have encountered an issue with getting the public methods to function properly. Despite all other logic working correctly, the public methods are not respondi ...