74770

JSON Get parent object from child object

Question:

How can I get <strong>discount</strong> value if <strong>brand_id=='983'</strong>.

Sample JSON:

{ "prods": [ { "info": { "rate": 100 }, "grocery": [ { "brand": "A", "brand_id": "983" }, { "brand": "B", "brand_id": "253" } ], "discount": "20" } ] }

What I have tried till now is

$.prods[*].grocery[?(@.brand_id=='983')]

This returns me list/array of matched objects. But I am not able to traverse back into the tree. Any help on this?

Answer1:

Indeed, JSONPath isn't very good at that, so I tackled this kind of problem with my own small library; so, here's a fiddle for your example:

<a href="https://jsfiddle.net/YSharpLanguage/j9oetwnn/3" rel="nofollow">https://jsfiddle.net/YSharpLanguage/j9oetwnn/3</a>

where:

var products = { "prods": [ { "info": { "rate": 85 }, "grocery": [ { "brand": "C", "brand_id": "984" }, { "brand": "D", "brand_id": "254" } ], "discount": "15" }, { "info": { "rate": 100 }, "grocery": [ { "brand": "A", "brand_id": "983" }, { "brand": "B", "brand_id": "253" } ], "discount": "20" } ] }; function GroceryItem(obj) { return (typeof obj.brand === "string") && (typeof obj.brand_id === "string"); } // last parameter set to "true", to grab all the "GroceryItem" instances // at any depth: var itemsAndDiscounts = [ products ].nodeset(GroceryItem, true). map( function(node) { var item = node.value, // node.value: the current "GroceryItem" (aka "$.prods[*].grocery[*]") discount = node.parent. // node.parent: the array of "GroceryItem" (aka "$.prods[*].grocery") parent. // node.parent.parent: the product (aka "$.prods[*]") discount; // node.parent.parent.discount: the product discount // finally, project into an easy-to-filter form: return { id: item.brand_id, discount: discount }; } ), discountOfItem983; discountOfItem983 = itemsAndDiscounts. filter ( function(mapped) { return mapped.id === "983"; } ) [0].discount; console.log("All items and discounts: " + JSON.stringify(itemsAndDiscounts, null, 2)); console.log("Discount of #983: " + discountOfItem983);

gives:

All items and discounts: [ { "id": "984", "discount": "15" }, { "id": "254", "discount": "15" }, { "id": "983", "discount": "20" }, { "id": "253", "discount": "20" } ] Discount of #983: 20

Here are other examples / use cases:

<h2>JSON-to-some-markup</h2>

<a href="https://jsfiddle.net/YSharpLanguage/kj9pk8oz/10" rel="nofollow">JSON transformations, revisited (XSLT look-alike)</a>

(at: <a href="https://jsfiddle.net/YSharpLanguage/kj9pk8oz/10" rel="nofollow">https://jsfiddle.net/YSharpLanguage/kj9pk8oz/10</a>)

<h2>JSON-to-JSON</h2>

<a href="https://jsfiddle.net/YSharpLanguage/ppfmmu15/10" rel="nofollow">Super-lightweight JSON-to-JSON transformations</a>

(at: <a href="https://jsfiddle.net/YSharpLanguage/ppfmmu15/10" rel="nofollow">https://jsfiddle.net/YSharpLanguage/ppfmmu15/10</a>)

<h2>A JavaScript equivalent of...</h2>

<a href="http://jsfiddle.net/YSharpLanguage/8bqcd0ey/1" rel="nofollow">XSLT 3.0 REC Section 14.4 Example: Grouping Nodes based on Common Values</a>

(at: <a href="http://jsfiddle.net/YSharpLanguage/8bqcd0ey/1" rel="nofollow">http://jsfiddle.net/YSharpLanguage/8bqcd0ey/1</a>)

Cf. <a href="https://www.w3.org/TR/xslt-30/#grouping-examples" rel="nofollow">https://www.w3.org/TR/xslt-30/#grouping-examples</a>

<h2>A JavaScript equivalent of...</h2>

<a href="https://jsfiddle.net/YSharpLanguage/hvo24hmk/3" rel="nofollow">JSONiq Use Cases Section 1.1.2. Grouping Queries for JSON</a>

(at: <a href="https://jsfiddle.net/YSharpLanguage/hvo24hmk/3" rel="nofollow">https://jsfiddle.net/YSharpLanguage/hvo24hmk/3</a>)

Cf. <a href="http://jsoniq.org/docs/JSONiq-usecases/html-single/index.html#jsongrouping" rel="nofollow">http://jsoniq.org/docs/JSONiq-usecases/html-single/index.html#jsongrouping</a>

'Hope this helps,

Answer2:

You can write a function that returns the parent node. Once you have that, you should develop a function that walks (traverses) all the object and all its nodes and arrays, and when it finds the desired Id, well, you just get the parent and retrieve for the discount.

Here you have the simplest example of a function that returns the parent node:

<pre class="snippet-code-js lang-js prettyprint-override">const myVar = { "prods": [{ "info": { "rate": 100 }, "grocery": [{ "brand": "A", "brand_id": "983", myParent: function() { const that = this; // to fix the caller instead of using 'bind' or 'apply' return that; } }, { "brand": "B", "brand_id": "253", myParent: function() { const that = this; return that; } } ], "discount": "20" }] } function myFunction() { let x = document.getElementById("myNumber").value; let text = myVar.prods[0].grocery.find(el => el.brand_id === x).myParent().brand; document.getElementById("demo").innerHTML = text; } <pre class="snippet-code-html lang-html prettyprint-override"><input type="number" id="myNumber" value="253"> <button onclick="myFunction()">Try it</button> <p id="demo">

Recommend

  • Opening modal from within a modal, backdrop z-index
  • A platform for easy creation of custom websites?
  • hyperledger-composer v1.1:unable to instantiate chaincode
  • Importing Excel Charts from Excel to PowerPoint causes `RPC_E_SERVERFAULT` on some machines
  • Subset data.table based on all possible combinations of two or more variables
  • How to create a graph and its schema without using Datastax Studio but through Java?
  • Angular 4 + Universal : Has no exported member 'StaticProvider'
  • Putting multiple films in a circle in Raphael/Joint.js
  • Eclipse ADT Plugin crashed after updating to version 22.0
  • Multiple custom authentication with spring security
  • Longest `subsequence` of balanced parentheses
  • web2py: How to execute instructions before delete using SQLFORM.smartgrid
  • Mask Image to Video Frame similar as MV Master
  • Pyinstaller GLIBC_2.15 not found
  • no endpoints available for service \\“kubernetes-dashboard\\”
  • Sprite animation wobbly / jumping in IE11
  • Planned Contrasts on glmmTMB
  • read.table returning character matrix, would like numeric
  • Combine two jagged lists into one
  • jQuery colorbox breaks postbacks in ASP.NET Web Forms
  • Slick: How can I combine a SQL LIKE statement with a SQL IN statement
  • Get name of days between two date in ios?
  • Allowing audio files in Spring MVC 3.0?
  • trigger ontouch event programmatically
  • Can I read another applications memory?
  • How to make 100% div height between header and footer?
  • Amazon Elastick BeanStalk error: Failed to create the AWS Elastic Beanstalk application version
  • Can a PHP script be scheduled to run at a specific time or after a specific amount of time has expir
  • Terminal run dalvikvm with am.jar
  • read part of h5 dataset python
  • ssh remote server login script
  • Capture SIGFPE from SIMD instruction
  • customize soft keyboard key preview
  • Using Service Component Runtime
  • Angular FormGroup won't update it's value immediately after patchValue or setValue
  • How do I use TagLib-Sharp to write custom (PRIV) ID3 frames?
  • Write to .csv file with PHP (Commas in Data Error)
  • CAS 4 - Not able to retrieve the LDAP groups after successful authentication
  • JavaScript RegExp Replace
  • ARKit code issue {unknown error -1=ffffffffffffffff error: Task failed with exit 1}