1

I have JSON returned from an API like below, where I want to fetch data of the latest date say 2022-01-13 in XML. Please can you guide me

daywisedata": {

        "2022-01-11": {
            "total_earning": 10,            
            "total_cost": 0
        },
        "2022-01-12": {
            "total_earning": 5,            
            "total_cost": 10
        },
        "2022-01-13": {
           "total_earning": 20,            
            "total_cost": 15
            }       
        }

XML needs to be returned like

 <daywisedata>
<total_earning> 20 </total_earning>            
<total_cost> 15 </total_cost> 
</daywisedata>
3
  • 1. Is the input sorted by date? 2. Why don't you post your attempt so we can fix it, instead of having to write your code for you from scratch. Commented Jan 25, 2022 at 5:29
  • Yes, input is sorted by date. Thanks Commented Jan 25, 2022 at 5:32
  • Well, then it should be easy to isolate the last entry. Commented Jan 25, 2022 at 5:35

1 Answer 1

1

Consider the following example:

XML (containing a valid(!) JSON)

<JSON>
{
    "daywisedata" : 
    {
        "2022-01-11" : 
        {
            "total_cost" : 0,
            "total_earning" : 10
        },
        "2022-01-12" : 
        {
            "total_cost" : 10,
            "total_earning" : 5
        },
        "2022-01-13" : 
        {
            "total_cost" : 15,
            "total_earning" : 20
        }
    }
}
</JSON>

XSLT 3.0

<xsl:stylesheet version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="/">
    <xsl:variable name="map" select="parse-json(JSON)?daywisedata?*[last()]" />
    <results>
        <total_cost>
            <xsl:value-of select="$map?total_cost"/>
        </total_cost>
        <total_earning>
            <xsl:value-of select="$map?total_earning"/>
        </total_earning>
    </results>
</xsl:template>

</xsl:stylesheet>

Result

<?xml version="1.0" encoding="UTF-8"?>
<results>
   <total_cost>15</total_cost>
   <total_earning>20</total_earning>
</results>

Demo: https://xsltfiddle.liberty-development.net/3MXNWNB

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.