Using XSLT to generate default XML nodes when a corresponding JSON element is missing

I am working with JSON structured as follows:

{
  "Message" :
  {
    "dynamicFields" :
    [ {
      "alias" : "TEST_ALIAS",
      "value" : "VALUE"
      }
      ,
      {
      "alias" : "CAR",
      "value" : "TOYOTA"
      }
    ]
  }
}

My XSLT stylesheet is set up like this:

    <xsl:template match="j:map[j:string[@key='value' and text() !='']]">

        <xsl:if test="j:string[@key='alias' and text() != '']">
            
           <ns2:field name="{j:string[@key='alias']}">
                
               <xsl:value-of select="upper-case(j:string[@key='value'])"/>
            
           </ns2:field>
        
        </xsl:if>

    </xsl:template>

This setup creates elements such as:

 <ns2:field name="TEST_ALIAS">VALUE</ns2:field>

However, I am struggling to add xml nodes conditionally.

For instance, if a JSON element with an alias of CAR does not exist, it should be added with a default value.

If the JSON were to look like this:

{
  "Message" :
  {
    "dynamicFields" :
    [ {
      "alias" : "TEST_ALIAS",
      "value" : "VALUE"
      }
    ]
  }
}

The resulting XML should be:

 <ns2:field name="TEST_ALIAS">VALUE</ns2:field>
 <ns2:field name="CAR">DEFAULT_CAR_VALUE</ns2:field>

The only assumption I can make about the JSON data is that all elements will have both an alias key and a value key.

Answer №1

When working with XSLT, it's important to carefully consider how you structure your templates. One approach could be to enhance the template for the dynamicFields property by checking if the array contains an object with an alias of "CAR". If not, you can include a default element like

<ns2:field name="CAR"> DEFAULT_CAR_VALUE</ns2:field>
:

<xsl:template match="j:array[@key='dynamicFields']">
    <xsl:apply-templates />

    <xsl:variable name="default-field" select="'CAR'"/>
    
    <xsl:if test="not(j:map/j:string[@key='alias'] = $default-field)">
        <ns2:field name="{$default-field}">
            <xsl:text>DEFAULT_CAR_VALUE</xsl:text>
        </ns2:field>  
    </xsl:if>

</xsl:template>    

<xsl:template match="j:map[j:string[@key='value' and text() !='']]">
    <xsl:if test="j:string[@key='alias' and text() != '']">
        <ns2:field name="{j:string[@key='alias']}">
            <xsl:value-of select="upper-case(j:string[@key='value'])"/>
        </ns2:field>        
    </xsl:if>    
</xsl:template>

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

Modifying the key values of an associative array

In my code snippet, I am attempting to loop through a JSON array and update the values within it. Here is an overview of what the JSON structure looks like: <?php $json='[{"type":"dropdown","label":"Is the property tenanted ?","req":0,"choices":[{ ...

Converting UML diagrams into JSON Schema and XSD files

A simple UML diagram has been created as part of a larger cinema diagram. Link to Image Based on the diagram, Json Schema and XSD files were generated: Json Schema: -> movieSchema.json { "type": "object", "required": true, "properties" ...

Using AngularJS within XSLT: Unrecognized prefix 'true' encountered

I have a button that uses ng-repeat. Inside this button, I am applying an active class based on the default product. <button type="button" ng-model="selectedProductGroup" ng-repeat="item in pgroup |unique: 'Product' track by $index" ng-click= ...

I am looking to retrieve a sophisticated/nested JSON data using jQuery

I need some assistance in fetching specific JSON object data. Specifically, I am looking to extract the name, poster image URL, size of the second backdrop image, and version number. As a newcomer to JSON, I was wondering if there is an easy way for me to ...

Exploring Gson's method for deserializing JSON containing optional fields

I'm currently utilizing Gson for deserializing a JSON string obtained from an API using the code snippet below. Gson gson = new Gson(); Map<String, CustomDto> test = gson.fromJson(result, new TypeToken<Map<String, CustomDto>>() {}.g ...

after ajax post, enhance original object by merging with the latest server values

After making a call to the server and successfully saving some data, I need to update the JSON array object that I have with new values. Here is a snippet of my code: [ { "id": 1, "uuid": "ce54acea-db20-4716-bceb-2f3deb1b2b86", "name": null, ...

Using spaces in JSON key names can create potential compatibility issues

I have a JSON structure that needs to be displayed in a table with specific keys and values. The key names contain spaces, such as "PAY ALL", "PAY PART", "DECLINE", and I need to show the corresponding values for each in the table rows. How can I achieve t ...

Implement filtering for schema-less JSON objects within GraphQL

I am facing a challenge with a data JSON object that contains dynamic fields, making it impossible to define the schema in GraphQL. Instead, I defined it as Json using scalar. My goal is to filter the fields within the data JSON object. Here is an example ...

Navigating the challenge of managing a dynamically generated JSON name field

For instance: The name is 435150 and its values are success and data. If I request a different game, the name changes. Let's say 578080. public void readJson(String gameID) throws IOException { String targetURL = String.format(STEAM_API, ...

An ASMX web service encountering an unescaped double quote within a parameter while processing JSON data

Within my HTTP REQUEST, a valid JSON string is present with a double quote in the middle of the name "jo\"hn" escaped. This was captured by Fiddler Web Debugger. {"name":"firstName","value":"jo\"hn"}, It's important to note that the reques ...

There are various IDs in the output and I only require one specific ID

I have a JSON fetcher that is functioning properly. However, whenever I request an ID, it returns all the IDs present in the JSON data. Is there a way to retrieve only the latest ID? This is my first time working with JSON so I am still learning. $(docu ...

What is the process for associating JSON reponses with button actions on a webpage?

I developed a JavaScript script that interacts with a Tableau server API to handle running jobs. The script presents the retrieved jobs on a web page, along with corresponding buttons that enable users to terminate specific jobs. While the script function ...

Creating POJOs by parsing two JSON files, with one file referencing the other

I currently have two JSON files named occupations.json and people.json. The first file contains an array of occupations: [ { "name": "developer", "salary": "90000"}, { "name": "designer", "salary": "80000"}, { "name": "manager", "salary": "700 ...

Learn the process of converting C# code to Kotlin with the incorporation of a Json library

Hello, I am new to Kotlin and apologize for my poor English. I am trying to convert the code snippet below to Kotlin. However, I am having trouble finding the equivalent of [JsonExtensiondata] in Kotlin. public class ProofAttribute { [JsonProperty(&q ...

modifying Json fieldName twice

Can the field name in a JSON be changed twice in a Spring REST API? While it may not have much meaning, I require this functionality. For instance, consider the JSON received from the remote service: { total_count : 1; } The Model class is defined a ...

Utilize key value pairs to retrieve data from a multi-level array

I'm looking for assistance with extracting values from an array based on key value rather than array number. $json = json_decode($stock, true); print_r($json); $sims = $json['stock'][1]['sims']; foreach ($sims as $sim) { echo ...

Sending JSON information from the App Component to a different component within Angular 6

I am faced with a challenge involving two components: 1. App Component 2. Main Component Within app.component.ts: ngOnInit () { this.httpService.get('./assets/batch_json_data.json').subscribe(data => { this.batchJson = data ...

Customizing response headers in vanilla Node.js

My Node.js setup involves the following flow: Client --> Node.js --> External Rest API The reverse response flow is required. To meet this requirement, I am tasked with capturing response headers from the External Rest API and appending them to Nod ...

Ways to incorporate JSON web token into every query string of my requests

Just recently, I grasped the concept of using JSON web tokens. Successfully, I can generate a JSON web token upon sign-in and have also established the middleware to authenticate my token and secure the routes that fall under the JSON verification middlewa ...

Retrieve keys only in a concise list using JQ

I am working with a Pipfile.lock JSON file that requires parsing using the jq tool. The format of the file is as follows: { //... "default": { "value1": { // numerous nested properties with values ...