简体   繁体   中英

How can I get the value of a JSON field in XSLT?

I would like to fetch the below text via xslt. Input is -

{
   "Contact Id":"3333333333",
   "Contact No":"9811430620",
   "Email Id":"abhishek.jain@homecredit.co.in",
   "Last Name":"Jain","First Name":"Abhishek"
}

Now i need only this text in output : 3333333333 .

Pls do let me know how to do in xslt.

Thanks

Well the input is not XML but JSON it seems so you might need to use an XSLT 3.0 processor like Saxon 9.6 PE or EE and the json-to-xml functionality

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">
    <xsl:output method="text" />

    <xsl:template match="json">
        <xsl:value-of select="json-to-xml(.)//*[@key = 'Contact Id']"/>
    </xsl:template>
</xsl:transform>

That assumes that your input actually has the JSON inside of an XML input element <json>{"Contact Id":"3333333333","Contact No":"9811430620","Email Id":"abhishek.jain@homecredit.co.in","Last Name":"Jain","First Name":"Abhishek"}</json> , if not, you would need to use json-to-xml(unparsed-text('file.json'))//*[@key = 'Contact Id'] .

This looks like JSON data. You tagged your question as XSLT 2.0, but if your processor is capable with , you can use parse-json() to get a map, or json-to-xml() to apply templates to it.

Other than that, it gets a bit ugly by using regexes, ie something like:

<xsl:value-of select="replace(., '.*Contact Id.:.(\d+).*', '$1')" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM