XML to Json Mapping -Data weave script filtration on indexing

194 Views Asked by At

I have to implement small logic in my code - here I am getting an XML request and it has to be converted into JSON. Before converting I have to implement small logic and my input XML is :

<details>
  <mydetail>
    <Firstdate>2017</Firstdate>
    <futuredate>1</futuredate>
  </mydetail>
  <mydetail>
    <Firstdate>2017</Firstdate>
    <futuredate>2</futuredate>
  </mydetail>
  <mydetail>
    <Firstdate>2017</Firstdate>
    <futuredate>3</futuredate>
  </mydetail>
</details>

and my expected JSON is:

[
  {
    "Currentdate": "2017",
    "Nextdate: null

  },
  {
   "Currentdate": "2017",
    "Nextdate "1"
  },
 {
    "Currentdate": "2017",
    "Nextdate "2"
  }
]

Logic Is:
In response, if it is the first Nextdate in JSON then it will always be null else Nextdate will map to the previous value of futuredate.

I have written below data weave script, but it is not working.

payload.details.*mydetail map {
    Currentdate: $.Firstdate,
    Nextdate: null when $$==0 otherwise $.Seconddate [$$-1]  ,
}

But this script is not working and I'm not getting the expected result.
What could be the reason for this error?

1

There are 1 best solutions below

2
On BEST ANSWER

Use following script to get desired output

%dw 1.0
%output application/json
---
payload.details.*mydetail map  {
    Currentdate: $.Firstdate,
    Nextdate: null when $$ == 0 otherwise payload.details.*mydetail.futuredate[$$ - 1]  
}

Your script is having extra , while mapping Nextdate which caused error.