Displaying artist data from network response via Spotify API - reactjs

Here is my Code.
spotifyApi.getMyCurrentPlaybackState()
.then((response) => {
this.setState({
nowPlaying: {
name: response.item.name,
artist: response.item.artists.name,
albumArt: response.item.album.images[0].url
}
});
})
my response object for 'artist:' is not displaying the artists' name. How can I change
artist: response.item.artists.name,
to get "Key Glock" to display?
Here is the network response data.
"item" : {
"album" : {
"album_type" : "album",
"artists" : [ {
"external_urls" : {
"spotify" : "https://open.spotify.com/artist/0RESbWvOMyua0yuyVrztJ5"
},
"href" : "https://api.spotify.com/v1/artists/0RESbWvOMyua0yuyVrztJ5",
"id" : "0RESbWvOMyua0yuyVrztJ5",
"name" : "Key Glock",
"type" : "artist",
"uri" : "spotify:artist:0RESbWvOMyua0yuyVrztJ5"
} ],
"available_markets" : [ "AD", "AE", "AG", "AL", "AM", "AO", "AR", "AT", "AU", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BN", "BO", "BR", "BS", "BT", "BW", "BY", "BZ", "CA", "CD", "CG", "CH", "CI", "CL", "CM", "CO", "CR", "CV", "CW", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "ES", "FI", "FJ", "FM", "FR", "GA", "GB", "GD", "GE", "GH", "GM", "GN", "GQ", "GR", "GT", "GW", "GY", "HK", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IN", "IQ", "IS", "IT", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KR", "KW", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MG", "MH", "MK", "ML", "MN", "MO", "MR", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NE", "NG", "NI", "NL", "NO", "NP", "NR", "NZ", "OM", "PA", "PE", "PG", "PH", "PK", "PL", "PS", "PT", "PW", "PY", "QA", "RO", "RS", "RU", "RW", "SA", "SB", "SC", "SE", "SG", "SI", "SK", "SL", "SM", "SN", "SR", "ST", "SV", "SZ", "TD", "TG", "TH", "TJ", "TL", "TN", "TO", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "US", "UY", "UZ", "VC", "VE", "VN", "VU", "WS", "XK", "ZA", "ZM", "ZW" ],
"external_urls" : {
"spotify" : "https://open.spotify.com/album/7snqOEQEtKqxJw3NTGml6i"

artists is an array, presumably the spotify API would return multiple artists if you had two or more artists on a track, which we would normally write "Jim feat. John".
To get the first artist's name: response.item.album.artists[0].name
To get all the artists' names: response.item.album.artists.map(curr => curr.name)

Related

XSLT to convert XML to JSON Array

I am currently using SAP CPI to achieve this conversion. I have tried the regular XML to JSON converter available but was not able to achieve this requirement. I then set out to try and see if XSLT can help.
I am trying to convert the following XML payload:
<root>
<ClientID>1</ClientID>
<PackageID>650</PackageID>
<SBUID>2187</SBUID>
<CandidateID>456</CandidateID>
<AssociateId>789</AssociateId>
<FirstName>Meghana</FirstName>
<MiddleName></MiddleName>
<LastName>Rao</LastName>
<FatherName>Satish</FatherName>
<ContactNo>7530001169</ContactNo>
<EmailID>dummy#sap.com</EmailID>
<AddressHistory>
<Address>
<SequenceNo>0</SequenceNo>
<AddressLine>Kharghar,navi mumbai</AddressLine>
<City>Maharashtra-Mumbai</City>
<State>Maharashtra</State>
<PinCode>410210</PinCode>
<Country>India</Country>
<Landmark></Landmark>
<StayFrom>01-08-2013</StayFrom>
<StayTo>06-08-2021</StayTo>
<IsCurrentAddress>false</IsCurrentAddress>
<IsPermanentAddress>false</IsPermanentAddress>
<HouseNo></HouseNo>
<AddressType>Current</AddressType>
<DocList>
<listofdocs>
<DocumentName>abc.jpg</DocumentName>
<DocumentPath>base64</DocumentPath>
</listofdocs>
</DocList>
</Address>
</AddressHistory>
<EducationList>
<Education>
<SequenceNo>0</SequenceNo>
<Qualification></Qualification>
<Degree>Under Graduate Degree</Degree>
<CollegeName>Amrutvahini College of engineering, Sangamner (Pune University)</CollegeName>
<Location></Location>
<RollNumber>123123</RollNumber>
<UniversityName>Mumbai University</UniversityName>
<UniversityAddress></UniversityAddress>
<PeriodFrom></PeriodFrom>
<PeriodTo></PeriodTo>
<YearOfPassing>2014</YearOfPassing>
<Zipcode></Zipcode>
<Percentage></Percentage>
<AdditionalRemarks>10th/12th/Undergrad etc</AdditionalRemarks>
<International>false</International>
<Country></Country>
<DocList>
<listofdocs>
<DocumentName>abc.jpg</DocumentName>
<DocumentPath>base64</DocumentPath>
</listofdocs>
</DocList>
</Education>
</EducationList>
<EmploymentList>
<Employment>
<SequenceNo>0</SequenceNo>
<EmployerName>Stravis Solutions</EmployerName>
<EmployerAddress>Bangalore</EmployerAddress>
<EmployerContactNo></EmployerContactNo>
<Designation>SDE</Designation>
<EmployeeID>asdas</EmployeeID>
<FixedSalary>0</FixedSalary>
<IsCurrentEmployment>false</IsCurrentEmployment>
<RelievingDate>15-10-2021</RelievingDate>
<State></State>
<City></City>
<Zipcode></Zipcode>
<International>false</International>
<Country></Country>
<PFNumber></PFNumber>
<UANNumber></UANNumber>
<DocList>
<listofdocs>
<DocumentName>abc.jpg</DocumentName>
<DocumentPath>base64</DocumentPath>
</listofdocs>
</DocList>
<DateOfJoining>18-03-2015</DateOfJoining>
</Employment>
<Employment>
<SequenceNo>0</SequenceNo>
<EmployerName>Stravis Solutions</EmployerName>
<EmployerAddress>Bangalore</EmployerAddress>
<EmployerContactNo></EmployerContactNo>
<Designation>SDE</Designation>
<EmployeeID>asdas</EmployeeID>
<FixedSalary>0</FixedSalary>
<IsCurrentEmployment>false</IsCurrentEmployment>
<RelievingDate>15-10-2021</RelievingDate>
<International>false</International>
<Country></Country>
<PFNumber></PFNumber>
<UANNumber></UANNumber>
<DocList>
<listofdocs>
<DocumentName>abc.jpg</DocumentName>
<DocumentPath>base64</DocumentPath>
</listofdocs>
</DocList>
<DateOfJoining>18-03-2015</DateOfJoining>
</Employment>
</EmploymentList>
<AddressReferencesList>
<ListofReferences>
<OrganizationName>Com 1</OrganizationName>
<AdditionalRemarks></AdditionalRemarks>
<NameOfReferee>Ref1</NameOfReferee>
<RefereeOccupation>SDE</RefereeOccupation>
<RefereePhoneNumber>123456</RefereePhoneNumber>
<RefereeEmailAddress>Ref1#com1.com</RefereeEmailAddress>
</ListofReferences>
<ListofReferences>
<OrganizationName>Com 1</OrganizationName>
<AdditionalRemarks></AdditionalRemarks>
<NameOfReferee>Ref1</NameOfReferee>
<RefereeOccupation>SDE</RefereeOccupation>
<RefereePhoneNumber>123456</RefereePhoneNumber>
<RefereeEmailAddress>Ref1#com1.com</RefereeEmailAddress>
</ListofReferences>
</AddressReferencesList>
<DOB>03-08-2021</DOB>
<DLDetails>
<DOB>03-08-2021</DOB>
<ApplicantName>Test</ApplicantName>
<FatherName>Test</FatherName>
<dl_remarks></dl_remarks>
<UniqueIDCode>1231231</UniqueIDCode>
<DocList>
<listofdocs>
<DocumentName>abc.jpg</DocumentName>
<DocumentPath>base64</DocumentPath>
</listofdocs>
</DocList>
</DLDetails>
<PanDetails>
<DOB>03-08-2021</DOB>
<ApplicantName>Sunil Kumar Yadav</ApplicantName>
<FatherName>Sunil</FatherName>
<pan_remarks></pan_remarks>
<UniqueIDCode>23123131</UniqueIDCode>
<DocList>
<listofdocs>
<DocumentName>abc.jpg</DocumentName>
<DocumentPath>base64</DocumentPath>
</listofdocs>
</DocList>
</PanDetails>
<PVWDetails>
<AddressList>
<Address>
<SequenceNo>0</SequenceNo>
<AddressLine>Kharghar,navi mumbai</AddressLine>
<City>Maharashtra-Mumbai</City>
<State>Maharashtra</State>
<PinCode>410210</PinCode>
<Country>India</Country>
<Landmark></Landmark>
<StayFrom>01-08-2013</StayFrom>
<StayTo>06-08-2021</StayTo>
<IsCurrentAddress>false</IsCurrentAddress>
<IsPermanentAddress>false</IsPermanentAddress>
<HouseNo>Sai shradha CHS.Sector-11,</HouseNo>
<AddressType>Current</AddressType>
<DocList>
<listofdocs>
<DocumentName>abc.jpg</DocumentName>
<DocumentPath>base64</DocumentPath>
</listofdocs>
</DocList>
</Address>
</AddressList>
<DOB>03-08-2021</DOB>
<FatherName>Sunil</FatherName>
<ApplicantName>Sunil Kumar Yadav</ApplicantName>
</PVWDetails>
<CreditDetail>
<ApplicantName>Test</ApplicantName>
<DOB>03-08-2021</DOB>
<FatherName>Test</FatherName>
<Gender>Male</Gender>
<UniqueIDCode>Pan Number</UniqueIDCode>
<EmailID>asda#gmail.com</EmailID>
<DocList>
<listofdocs>
<DocumentName>abc.jpg</DocumentName>
<DocumentPath>base64</DocumentPath>
</listofdocs>
</DocList>
</CreditDetail>
<DrugTestPanelCheck>
<DrugTestPanel>DrugTestPanel5</DrugTestPanel>
<ApplicantName>Test Candidate</ApplicantName>
</DrugTestPanelCheck>
<GDCDetails>
<ApplicantName>Sunil Kumar Yadav</ApplicantName>
<DOB>03-08-2021</DOB>
<FatherName>Sunil</FatherName>
</GDCDetails>
<PassportCheckDetails>
<NameInPassport>Sunil Kumar Yadav</NameInPassport>
<PassportNo>1231231</PassportNo>
<MachineReadableZone></MachineReadableZone>
<CandidateFirstName>Sunil</CandidateFirstName>
<CandidateLastName>Yadav</CandidateLastName>
<DOB>03-08-2021</DOB>
<FatherName>Sunil</FatherName>
<DocList>
<listofdocs>
<DocumentName>abc.jpg</DocumentName>
<DocumentPath>base64</DocumentPath>
</listofdocs>
</DocList>
</PassportCheckDetails>
</root>
To the below JSON payload, which as you can see has multiple array elements for even single payloads:
{
"ClientID": "1",
"PackageID": "650",
"SBUID": "2187",
"CandidateID": "456",
"AssociateId": "789",
"FirstName": "Meghana",
"MiddleName": "",
"LastName": "Rao",
"FatherName": "Satish",
"ContactNo": "7530001169",
"EmailID": "dummy#sap.com",
"AddressHistory": {
"Address": [
{
"SequenceNo": "0",
"AddressLine": "Kharghar,navi mumbai",
"City": "Maharashtra-Mumbai",
"State": "Maharashtra",
"PinCode": "410210",
"Country": "India",
"Landmark": "",
"StayFrom": "01-08-2013",
"StayTo": "06-08-2021",
"IsCurrentAddress": false,
"IsPermanentAddress": false,
"HouseNo": "",
"AddressType": "Current",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
}
}
]
},
"EducationList": {
"Education": [
{
"SequenceNo": "0",
"Qualification": "",
"Degree": "Under Graduate Degree",
"CollegeName": "Amrutvahini College of engineering, Sangamner (Pune University)",
"Location": "",
"RollNumber": "123123",
"UniversityName": "Mumbai University",
"UniversityAddress": "",
"PeriodFrom": "",
"PeriodTo": "",
"YearOfPassing": "2014",
"Zipcode": "",
"Percentage": "",
"AdditionalRemarks": "10th/12th/Undergrad etc",
"International": false,
"Country": "",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
}
}
]
},
"EmploymentList": {
"Employment": [
{
"SequenceNo": "0",
"EmployerName": "Stravis Solutions",
"EmployerAddress": "Bangalore",
"EmployerContactNo": "",
"Designation": "SDE",
"EmployeeID": "asdas",
"FixedSalary": "0",
"IsCurrentEmployment": false,
"RelievingDate": "15-10-2021",
"Zipcode": "",
"International": false,
"Country": "",
"PFNumber": "",
"UANNumber": "",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
},
"DateOfJoining": "18-03-2015"
},
{
"SequenceNo": "0",
"EmployerName": "Stravis Solutions",
"EmployerAddress": "Bangalore",
"EmployerContactNo": "",
"Designation": "SDE",
"EmployeeID": "asdas",
"FixedSalary": "0",
"IsCurrentEmployment": false,
"RelievingDate": "15-10-2021",
"Zipcode": "",
"International": false,
"Country": "",
"PFNumber": "",
"UANNumber": "",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
},
"DateOfJoining": "18-03-2015"
}
]
},
"AddressReferencesList": {
"ListofReferences": [
{
"OrganizationName": "Com 1",
"AdditionalRemarks": "",
"NameOfReferee": "Ref1",
"RefereeOccupation": "SDE",
"RefereePhoneNumber": "123456",
"RefereeEmailAddress": "Ref1#com1.com"
},
{
"OrganizationName": "Com 1",
"AdditionalRemarks": "",
"NameOfReferee": "Ref2",
"RefereeOccupation": "SDE",
"RefereePhoneNumber": "123456",
"RefereeEmailAddress": "Ref1#com1.com"
}
]
},
"DOB": "03-08-2021",
"DLDetails": {
"DOB": "03-08-2021",
"ApplicantName": "Test",
"FatherName": "Test",
"UniqueIDCode": "1231231",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
}
},
"PanDetails": {
"DOB": "03-08-2021",
"ApplicantName": "Sunil Kumar Yadav",
"FatherName": "Sunil",
"UniqueIDCode": "23123131",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
}
},
"PVWDetails": {
"AddressList": {
"Address": [
{
"SequenceNo": "0",
"AddressLine": "Kharghar,navi mumbai",
"City": "Maharashtra-Mumbai",
"State": "Maharashtra",
"PinCode": "410210",
"Country": "India",
"Landmark": "",
"StayFrom": "01-08-2013",
"StayTo": "06-08-2021",
"IsCurrentAddress": false,
"IsPermanentAddress": false,
"HouseNo": "Sai shradha CHS.Sector-11,",
"AddressType": "Current",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
}
}
]
},
"DOB": "03-08-2021",
"FatherName": "Sunil",
"ApplicantName": "Sunil Kumar Yadav"
},
"CreditDetail": {
"ApplicantName": "Test",
"DOB": "03-08-2021",
"FatherName": "Test",
"Gender": "Male",
"UniqueIDCode": "Pan Number",
"EmailID": "asda#gmail.com",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
}
},
"PassportCheckDetails": {
"NameInPassport": "Sunil Kumar Yadav",
"PassportNo": "1231231",
"MachineReadableZone": "",
"CandidateFirstName": "Sunil",
"CandidateLastName": "Yadav",
"DOB": "03-08-2021",
"FatherName": "Sunil",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
}
}
}
As you can see, there is an array created for every part of the data. How can I achieve this with XSLT?
Whatever code i have tried with so far, the converted JSON has not had any arrays barring cases where there are multiple records under a root.
I have tried variations of the following code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns0="http://use your namespace">
<xsl:output method="text"/>
<xsl:template match="/ns0:Account_Resp">{
<xsl:apply-templates select="*"/> }
</xsl:template>
<!-- Object or Element Property-->
<xsl:template match="*">
"<xsl:value-of select="name()"/>" : <xsl:call-template name="Properties"/>
</xsl:template>
<!-- Array Element -->
<xsl:template match="*" mode="ArrayElement">
<xsl:call-template name="Properties"/>
</xsl:template>
<!-- Object Properties -->
<xsl:template name="Properties">
<xsl:variable name="childName" select="name(*[1])"/>
<xsl:choose>
<xsl:when test="not(*|#*)">"<xsl:value-of select="."/>"</xsl:when>
<xsl:when test="count(*[name()=$childName]) > 1">{ "<xsl:value-of select="$childName"/>" :[<xsl:apply-templates select="*" mode="ArrayElement"/>] }</xsl:when>
<xsl:otherwise>{
<xsl:apply-templates select="#*"/>
<xsl:apply-templates select="*"/>
}</xsl:otherwise>
</xsl:choose>
<xsl:if test="following-sibling::*">,</xsl:if>
</xsl:template>
<!-- Attribute Property -->
<xsl:template `enter code here`match="#*">"<xsl:value-of select="name()"/>" : "<xsl:value-of select="."/>",
</xsl:template>
</xsl:stylesheet>
And received the following output - in which you can see that for single payloads, an array is not getting created:
{
"ClientID" : "1",
"PackageID" : "650",
"SBUID" : "2187",
"CandidateID" : "456",
"AssociateId" : "789",
"FirstName" : "Meghana",
"MiddleName" : "",
"LastName" : "Rao",
"FatherName" : "Satish",
"ContactNo" : "7530001169",
"EmailID" : "dummy#sap.com",
"AddressHistory" : { "Address" :[{
"SequenceNo" : "0",
"AddressLine" : "Kharghar,navi mumbai",
"City" : "Maharashtra-Mumbai",
"State" : "Maharashtra",
"PinCode" : "410210",
"Country" : "India",
"Landmark" : "",
"StayFrom" : "01-08-2013",
"StayTo" : "06-08-2021",
"IsCurrentAddress" : "false",
"IsPermanentAddress" : "false",
"HouseNo" : "",
"AddressType" : "Current",
"DocList" : { "listofdocs" :[{
"DocumentName" : "abc.jpg",
"DocumentPath" : "base64"
}] }
},{
"SequenceNo" : "1",
"AddressLine" : "Kharghar,navi mumbai",
"City" : "Maharashtra-Mumbai",
"State" : "Maharashtra",
"PinCode" : "410210",
"Country" : "India",
"Landmark" : "",
"StayFrom" : "01-08-2013",
"StayTo" : "06-08-2021",
"IsCurrentAddress" : "false",
"IsPermanentAddress" : "false",
"HouseNo" : "",
"AddressType" : "Current",
"DocList" : { "listofdocs" :[{
"DocumentName" : "def.jpg",
"DocumentPath" : "base64"
}] }
}] },
"EducationList" : {
"Education" : {
"SequenceNo" : "0",
"Qualification" : "",
"Degree" : "Under Graduate Degree",
"CollegeName" : "Amrutvahini College of engineering, Sangamner (Pune University)",
"Location" : "",
"RollNumber" : "123123",
"UniversityName" : "Mumbai University",
"UniversityAddress" : "",
"PeriodFrom" : "",
"PeriodTo" : "",
"YearOfPassing" : "2014",
"Percentage" : "",
"AdditionalRemarks" : "10th/12th/Undergrad etc",
"International" : "false",
"Country" : "",
"DocList" : { "listofdocs" :[{
"DocumentName" : "def.jpg",
"DocumentPath" : "base64"
}] }
}
},
"EmploymentList" : { "Employment" :[{
"SequenceNo" : "0",
"EmployerName" : "Stravis Solutions",
"EmployerAddress" : "Bangalore",
"EmployerContactNo" : "",
"Designation" : "SDE",
"EmployeeID" : "asdas",
"FixedSalary" : "0",
"IsCurrentEmployment" : "false",
"RelievingDate" : "15-10-2021",
"Zipcode" : "",
"International" : "false",
"Country" : "",
"PFNumber" : "",
"UANNumber" : "",
"DocList" : {
"listofdocs" : {
"DocumentName" : "abc.jpg",
"DocumentPath" : "base64"
}
},
"DateOfJoining" : "18-03-2015"
},{
"SequenceNo" : "1",
"EmployerName" : "Stravis Solutions",
"EmployerAddress" : "Bangalore",
"EmployerContactNo" : "",
"Designation" : "SDE",
"EmployeeID" : "asdas",
"FixedSalary" : "0",
"IsCurrentEmployment" : "false",
"RelievingDate" : "15-10-2021",
"Zipcode" : "",
"International" : "false",
"Country" : "",
"PFNumber" : "",
"UANNumber" : "",
"DocList" : {
"listofdocs" : {
"DocumentName" : "def.jpg",
"DocumentPath" : "base64"
}
},
"DateOfJoining" : "18-03-2015"
}] },
"AddressReferencesList" : { "ListofReferences" :[{
"OrganizationName" : "Com 1",
"AdditionalRemarks" : "",
"NameOfReferee" : "Ref1",
"RefereeOccupation" : "SDE",
"RefereePhoneNumber" : "123456",
"RefereeEmailAddress" : "Ref1#com1.com"
},{
"OrganizationName" : "Com 1",
"AdditionalRemarks" : "",
"NameOfReferee" : "Ref2",
"RefereeOccupation" : "SDE",
"RefereePhoneNumber" : "123456",
"RefereeEmailAddress" : "Ref1#com1.com"
}] },
"DOB" : "03-08-2021",
"DLDetails" : {
"DOB" : "03-08-2021",
"ApplicantName" : "Test",
"FatherName" : "Test",
"UniqueIDCode" : "1231231",
"DocList" : {
"listofdocs" : {
"DocumentName" : "abc.jpg",
"DocumentPath" : "base64"
}
}
},
"PanDetails" : {
"DOB" : "03-08-2021",
"ApplicantName" : "Sunil Kumar Yadav",
"FatherName" : "Sunil",
"UniqueIDCode" : "23123131",
"DocList" : {
"listofdocs" : {
"DocumentName" : "abc.jpg",
"DocumentPath" : "base64"
}
}
},
"PVWDetails" : {
"AddressList" : {
"Address" : {
"SequenceNo" : "0",
"AddressLine" : "Kharghar,navi mumbai",
"City" : "Maharashtra-Mumbai",
"State" : "Maharashtra",
"PinCode" : "410210",
"Country" : "India",
"Landmark" : "",
"StayFrom" : "01-08-2013",
"StayTo" : "06-08-2021",
"IsCurrentAddress" : "false",
"IsPermanentAddress" : "false",
"HouseNo" : "Sai shradha CHS.Sector-11,",
"AddressType" : "Current"
}
},
"DOB" : "03-08-2021",
"FatherName" : "Sunil",
"ApplicantName" : "Sunil Kumar Yadav"
},
"CreditDetail" : {
"ApplicantName" : "Test",
"DOB" : "03-08-2021",
"FatherName" : "Test",
"Gender" : "Male",
"UniqueIDCode" : "Pan Number",
"EmailID" : "asda#gmail.com",
"DocList" : {
"listofdocs" : {
"DocumentName" : "abc.jpg",
"DocumentPath" : "base64"
}
}
}, "DrugTestPanelCheck" : {
"DrugTestPanel" : "DrugTestPanel5",
"ApplicantName" : "Test Candidate"
},
"GDCDetails" : {
"ApplicantName" : "Sunil Kumar Yadav",
"DOB" : "03-08-2021",
"FatherName" : "Sunil"
},
"PassportCheckDetails" : {
"NameInPassport" : "Sunil Kumar Yadav",
"PassportNo" : "1231231",
"MachineReadableZone" : "",
"CandidateFirstName" : "Sunil",
"CandidateLastName" : "Yadav",
"DOB" : "03-08-2021",
"FatherName" : "Sunil",
"DocList" : {
"listofdocs" : {
"DocumentName" : "abc.jpg",
"DocumentPath" : "base64"
}
}
}
}
Really need some help on this.
Thanks
In order to determine which XML elements can occur with cardinality 0..*, you look only at the actual cardinality in the payload by testing whether count(*[name()=$childName]) > 1. By this, you miss the fact that the <EducationList> is allowed to contain more than one <Education> (even if it contains only one in this particular payload instance).
A clean solution would require you to look at the XML schema (in the WSDL document, probably). But in this case, the following heuristics might suffice: If an element name ends with List, it contains children with cardinality 0..*. Therefore, replace the test count(*[name()=$childName]) > 1 with
substring(name(), string-length(name()) - 3, 4) = 'List'
With the YAML processor mikefarah/yq, you can convert XML to JSON and make some custom adoptions to the conversion:
yq --input-format xml --output-format json '
with(.root;
.AddressHistory.Address |= select(type == "!!map") |= [.] |
.EducationList.Education |= select(type == "!!map") |= [.] |
.EmploymentList.Employment |= select(type == "!!map") |= [.] |
.AddressReferencesList.ListofReferences |= select(type == "!!map") |= [.] |
.PVWDetails.AddressList.Address |= select(type == "!!map") |= [.]
)
' input.xml
For given paths the update operator |= wraps an object (select(type == "!!map")) into an array ([.]).
Add all elements that should be an array to the code.
With kislyuk/xq, you can solve it this way:
ARRAY_PATHS='
[
"root.AddressHistory.Address",
"root.EducationList.Education",
"root.EmploymentList.Employment",
"root.AddressReferencesList.ListofReferences",
"root.PVWDetails.AddressList.Address"
]
'
xq --argjson paths "$ARRAY_PATHS" '
. as $input
| reduce ($paths
| map(split(".") # split given paths by "."
| . as $p
| select($input | getpath($p) | type == "object")))[] # process only objects at the given paths (ignore arrays)
as $path
(.; setpath($path; [getpath($path)])) # wrap objects at the given paths in an array
' input.xml
All given paths are checked if the value is an object: select($input | getpath($p) | type == "object").
Objects are wrapped into an array setpath($path; [getpath($path)]).
This solution is more generic and failsafe, if a given path is missing in the input.
Output (both versions)
{
"root": {
"ClientID": "1",
"PackageID": "650",
"SBUID": "2187",
"CandidateID": "456",
"AssociateId": "789",
"FirstName": "Meghana",
"MiddleName": null,
"LastName": "Rao",
"FatherName": "Satish",
"ContactNo": "7530001169",
"EmailID": "dummy#sap.com",
"AddressHistory": {
"Address": [
{
"SequenceNo": "0",
"AddressLine": "Kharghar,navi mumbai",
"City": "Maharashtra-Mumbai",
"State": "Maharashtra",
"PinCode": "410210",
"Country": "India",
"Landmark": null,
"StayFrom": "01-08-2013",
"StayTo": "06-08-2021",
"IsCurrentAddress": "false",
"IsPermanentAddress": "false",
"HouseNo": null,
"AddressType": "Current",
"DocList": {
"listofdocs": {
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
}
}
]
},
"EducationList": {
"Education": [
{
"SequenceNo": "0",
"Qualification": null,
"Degree": "Under Graduate Degree",
"CollegeName": "Amrutvahini College of engineering, Sangamner (Pune University)",
"Location": null,
"RollNumber": "123123",
"UniversityName": "Mumbai University",
"UniversityAddress": null,
"PeriodFrom": null,
"PeriodTo": null,
"YearOfPassing": "2014",
"Zipcode": null,
"Percentage": null,
"AdditionalRemarks": "10th/12th/Undergrad etc",
"International": "false",
"Country": null,
"DocList": {
"listofdocs": {
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
}
}
]
},
"EmploymentList": {
"Employment": [
{
"SequenceNo": "0",
"EmployerName": "Stravis Solutions",
"EmployerAddress": "Bangalore",
"EmployerContactNo": null,
"Designation": "SDE",
"EmployeeID": "asdas",
"FixedSalary": "0",
"IsCurrentEmployment": "false",
"RelievingDate": "15-10-2021",
"State": null,
"City": null,
"Zipcode": null,
"International": "false",
"Country": null,
"PFNumber": null,
"UANNumber": null,
"DocList": {
"listofdocs": {
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
},
"DateOfJoining": "18-03-2015"
},
{
"SequenceNo": "0",
"EmployerName": "Stravis Solutions",
"EmployerAddress": "Bangalore",
"EmployerContactNo": null,
"Designation": "SDE",
"EmployeeID": "asdas",
"FixedSalary": "0",
"IsCurrentEmployment": "false",
"RelievingDate": "15-10-2021",
"International": "false",
"Country": null,
"PFNumber": null,
"UANNumber": null,
"DocList": {
"listofdocs": {
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
},
"DateOfJoining": "18-03-2015"
}
]
},
"AddressReferencesList": {
"ListofReferences": [
{
"OrganizationName": "Com 1",
"AdditionalRemarks": null,
"NameOfReferee": "Ref1",
"RefereeOccupation": "SDE",
"RefereePhoneNumber": "123456",
"RefereeEmailAddress": "Ref1#com1.com"
},
{
"OrganizationName": "Com 1",
"AdditionalRemarks": null,
"NameOfReferee": "Ref1",
"RefereeOccupation": "SDE",
"RefereePhoneNumber": "123456",
"RefereeEmailAddress": "Ref1#com1.com"
}
]
},
"DOB": "03-08-2021",
"DLDetails": {
"DOB": "03-08-2021",
"ApplicantName": "Test",
"FatherName": "Test",
"dl_remarks": null,
"UniqueIDCode": "1231231",
"DocList": {
"listofdocs": {
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
}
},
"PanDetails": {
"DOB": "03-08-2021",
"ApplicantName": "Sunil Kumar Yadav",
"FatherName": "Sunil",
"pan_remarks": null,
"UniqueIDCode": "23123131",
"DocList": {
"listofdocs": {
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
}
},
"PVWDetails": {
"AddressList": {
"Address": [
{
"SequenceNo": "0",
"AddressLine": "Kharghar,navi mumbai",
"City": "Maharashtra-Mumbai",
"State": "Maharashtra",
"PinCode": "410210",
"Country": "India",
"Landmark": null,
"StayFrom": "01-08-2013",
"StayTo": "06-08-2021",
"IsCurrentAddress": "false",
"IsPermanentAddress": "false",
"HouseNo": "Sai shradha CHS.Sector-11,",
"AddressType": "Current",
"DocList": {
"listofdocs": {
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
}
}
]
},
"DOB": "03-08-2021",
"FatherName": "Sunil",
"ApplicantName": "Sunil Kumar Yadav"
},
"CreditDetail": {
"ApplicantName": "Test",
"DOB": "03-08-2021",
"FatherName": "Test",
"Gender": "Male",
"UniqueIDCode": "Pan Number",
"EmailID": "asda#gmail.com",
"DocList": {
"listofdocs": {
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
}
},
"DrugTestPanelCheck": {
"DrugTestPanel": "DrugTestPanel5",
"ApplicantName": "Test Candidate"
},
"GDCDetails": {
"ApplicantName": "Sunil Kumar Yadav",
"DOB": "03-08-2021",
"FatherName": "Sunil"
},
"PassportCheckDetails": {
"NameInPassport": "Sunil Kumar Yadav",
"PassportNo": "1231231",
"MachineReadableZone": null,
"CandidateFirstName": "Sunil",
"CandidateLastName": "Yadav",
"DOB": "03-08-2021",
"FatherName": "Sunil",
"DocList": {
"listofdocs": {
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
}
}
}
}
The standard xml-to-json XSLT 3.0 function can meet your requirement. The complexity lies in establishing the transform rules for when to use JSON maps and arrays.
I inferred the transform rules from the supplied input XML and output JSON. These rules may need adjustment to cover cases not tested by your sample. Here's the main xsl:template instruction:
<xsl:template match="*[*]" mode="outer">
<xsl:param name="key" as="xs:string?"/>
<xsl:variable name="distinctChildNames" as="xs:string*" select="*!name() => distinct-values()"/>
<xsl:choose>
<xsl:when test="count($distinctChildNames) gt 1 and exists($key)">
<array>
<xsl:sequence select="fn:keyAttribute(name())"/>
<map>
<xsl:apply-templates select="*" mode="outer">
<xsl:with-param name="key" select="name()"/>
</xsl:apply-templates>
</map>
</array>
</xsl:when>
<xsl:when test="count(*) gt 1 and count($distinctChildNames) eq 1">
<map>
<xsl:sequence select="fn:keyAttribute(name())"/>
<array key="{name(*[1])}">
<xsl:for-each select="*">
<map>
<xsl:apply-templates select="*" mode="outer"/>
</map>
</xsl:for-each>
</array>
</map>
</xsl:when>
<xsl:otherwise>
<map>
<xsl:sequence select="fn:keyAttribute(name())"/>
<xsl:apply-templates select="*" mode="outer">
<xsl:with-param name="key" select="name()"/>
</xsl:apply-templates>
</map>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
The JSON output:
{
"ClientID": "1",
"PackageID": "650",
"SBUID": "2187",
"CandidateID": "456",
"AssociateId": "789",
"FirstName": "Meghana",
"MiddleName": "",
"LastName": "Rao",
"FatherName": "Satish",
"ContactNo": "7530001169",
"EmailID": "dummy#sap.com",
"AddressHistory": {
"Address": [
{
"SequenceNo": "0",
"AddressLine": "Kharghar,navi mumbai",
"City": "Maharashtra-Mumbai",
"State": "Maharashtra",
"PinCode": "410210",
"Country": "India",
"Landmark": "",
"StayFrom": "01-08-2013",
"StayTo": "06-08-2021",
"IsCurrentAddress": false,
"IsPermanentAddress": false,
"HouseNo": "",
"AddressType": "Current",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
}
}
]
},
"EducationList": {
"Education": [
{
"SequenceNo": "0",
"Qualification": "",
"Degree": "Under Graduate Degree",
"CollegeName": "Amrutvahini College of engineering, Sangamner (Pune University)",
"Location": "",
"RollNumber": "123123",
"UniversityName": "Mumbai University",
"UniversityAddress": "",
"PeriodFrom": "",
"PeriodTo": "",
"YearOfPassing": "2014",
"Zipcode": "",
"Percentage": "",
"AdditionalRemarks": "10th\/12th\/Undergrad etc",
"International": false,
"Country": "",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
}
}
]
},
"EmploymentList": {
"Employment": [
{
"SequenceNo": "0",
"EmployerName": "Stravis Solutions",
"EmployerAddress": "Bangalore",
"EmployerContactNo": "",
"Designation": "SDE",
"EmployeeID": "asdas",
"FixedSalary": "0",
"IsCurrentEmployment": false,
"RelievingDate": "15-10-2021",
"State": "",
"City": "",
"Zipcode": "",
"International": false,
"Country": "",
"PFNumber": "",
"UANNumber": "",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
},
"DateOfJoining": "18-03-2015"
},
{
"SequenceNo": "0",
"EmployerName": "Stravis Solutions",
"EmployerAddress": "Bangalore",
"EmployerContactNo": "",
"Designation": "SDE",
"EmployeeID": "asdas",
"FixedSalary": "0",
"IsCurrentEmployment": false,
"RelievingDate": "15-10-2021",
"International": false,
"Country": "",
"PFNumber": "",
"UANNumber": "",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
},
"DateOfJoining": "18-03-2015"
}
]
},
"AddressReferencesList": {
"ListofReferences": [
{
"OrganizationName": "Com 1",
"AdditionalRemarks": "",
"NameOfReferee": "Ref1",
"RefereeOccupation": "SDE",
"RefereePhoneNumber": "123456",
"RefereeEmailAddress": "Ref1#com1.com"
},
{
"OrganizationName": "Com 1",
"AdditionalRemarks": "",
"NameOfReferee": "Ref1",
"RefereeOccupation": "SDE",
"RefereePhoneNumber": "123456",
"RefereeEmailAddress": "Ref1#com1.com"
}
]
},
"DOB": "03-08-2021",
"DLDetails": {
"DOB": "03-08-2021",
"ApplicantName": "Test",
"FatherName": "Test",
"dl_remarks": "",
"UniqueIDCode": "1231231",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
}
},
"PanDetails": {
"DOB": "03-08-2021",
"ApplicantName": "Sunil Kumar Yadav",
"FatherName": "Sunil",
"pan_remarks": "",
"UniqueIDCode": "23123131",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
}
},
"PVWDetails": {
"AddressList": {
"Address": [
{
"SequenceNo": "0",
"AddressLine": "Kharghar,navi mumbai",
"City": "Maharashtra-Mumbai",
"State": "Maharashtra",
"PinCode": "410210",
"Country": "India",
"Landmark": "",
"StayFrom": "01-08-2013",
"StayTo": "06-08-2021",
"IsCurrentAddress": false,
"IsPermanentAddress": false,
"HouseNo": "Sai shradha CHS.Sector-11,",
"AddressType": "Current",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
}
}
]
},
"DOB": "03-08-2021",
"FatherName": "Sunil",
"ApplicantName": "Sunil Kumar Yadav"
},
"CreditDetail": {
"ApplicantName": "Test",
"DOB": "03-08-2021",
"FatherName": "Test",
"Gender": "Male",
"UniqueIDCode": "Pan Number",
"EmailID": "asda#gmail.com",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
}
},
"DrugTestPanelCheck": {
"DrugTestPanel": "DrugTestPanel5",
"ApplicantName": "Test Candidate"
},
"GDCDetails": {
"ApplicantName": "Sunil Kumar Yadav",
"DOB": "03-08-2021",
"FatherName": "Sunil"
},
"PassportCheckDetails": {
"NameInPassport": "Sunil Kumar Yadav",
"PassportNo": "1231231",
"MachineReadableZone": "",
"CandidateFirstName": "Sunil",
"CandidateLastName": "Yadav",
"DOB": "03-08-2021",
"FatherName": "Sunil",
"DocList": {
"listofdocs": [
{
"DocumentName": "abc.jpg",
"DocumentPath": "base64"
}
]
}
}
}
There are minor differences in the result:
The '/' character is escaped to \/ in the JSON output
JSON properties transformed from empty XML elements: the XSLT here always keeps the property and sets the value to an empty string
Here's the full XSLT used:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:fn="com.example.functions"
xmlns="http://www.w3.org/2005/xpath-functions"
expand-text="yes"
version="3.0">
<xsl:output method="text" indent="yes"/>
<xsl:mode on-no-match="shallow-copy"/>
<xsl:mode name="outer" on-no-match="shallow-copy"/>
<xsl:template match="/*">
<xsl:variable name="result" as="node()*">
<map>
<xsl:apply-templates select="*" mode="outer"/>
</map>
</xsl:variable>
<xsl:sequence select="xml-to-json($result)"/>
</xsl:template>
<xsl:template match="*[*]" mode="outer">
<xsl:param name="key" as="xs:string?"/>
<xsl:variable name="distinctChildNames" as="xs:string*" select="*!name() => distinct-values()"/>
<xsl:choose>
<xsl:when test="count($distinctChildNames) gt 1 and exists($key)">
<array>
<xsl:sequence select="fn:keyAttribute(name())"/>
<map>
<xsl:apply-templates select="*" mode="outer">
<xsl:with-param name="key" select="name()"/>
</xsl:apply-templates>
</map>
</array>
</xsl:when>
<xsl:when test="count(*) gt 1 and count($distinctChildNames) eq 1">
<map>
<xsl:sequence select="fn:keyAttribute(name())"/>
<array key="{name(*[1])}">
<xsl:for-each select="*">
<map>
<xsl:apply-templates select="*" mode="outer"/>
</map>
</xsl:for-each>
</array>
</map>
</xsl:when>
<xsl:otherwise>
<map>
<xsl:sequence select="fn:keyAttribute(name())"/>
<xsl:apply-templates select="*" mode="outer">
<xsl:with-param name="key" select="name()"/>
</xsl:apply-templates>
</map>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="*[empty(*) and exists(text())]" mode="outer">
<xsl:apply-templates select="node()" mode="outer">
<xsl:with-param name="key" select="name()"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="*[empty(*) and empty(text())]" mode="outer">
<string key="{name()}"/>
</xsl:template>
<xsl:template match="text()[. = ('true', 'false')]" mode="outer">
<xsl:param name="key" as="xs:string?"/>
<boolean key="{$key}">{.}</boolean>
</xsl:template>
<xsl:template match="text()" mode="outer">
<xsl:param name="key" as="xs:string?"/>
<xsl:if test="exists($key)">
<string key="{$key}">{.}</string>
</xsl:if>
</xsl:template>
<xsl:function name="fn:keyAttribute" as="attribute()?">
<xsl:param name="key" as="xs:string?"/>
<xsl:if test="$key">
<xsl:attribute name="key" select="$key"/>
</xsl:if>
</xsl:function>
</xsl:stylesheet>

How to create a JSON structure in ReactJS

I have a use-case to create a JSON structure in React in order to POST an API request. The JSON structure body contains objects and arrays.
Please let me know how to create it in ReactJS.
Below is the sample JSON structure that needs to be created using ReactJS:-
{
"transactionAmount": {
"currency": "INR",
"value": 1220.38
},
"transactionDate": "2020-05-18T00:00:00Z",
"tripData": {
"agencyBooked": false,
"legs": [
{
"endLocation": {
"countryCode": "IN",
"city": "Delhi",
"name": "Indira Gandhi International"
},
"startDate": "2020-05-22",
"startTime": "08:00",
"returnLeg": false,
"startLocation": {
"countryCode": "US",
"city": "San Francisco",
"name": "San Francisco International"
},
"endTime": "21:00",
"endDate": "2020-05-22",
"startLocationDetail": "none"
},
{
"endLocation": {
"countryCode": "US",
"city": "San Francisco",
"name": "San Francisco International"
},
"returnLeg": true,
"startDate": "2020-05-24",
"startLocation": {
"countryCode": "IN",
"city": "Delhi",
"name": "Indira Gandhi International"
},
"startTime": "17:00"
}
],
"segmentType": {
"category": "REQ_SEG_AIRFR",
"code": "AIRFR"
},
"selfBooked": false,
"tripType": "ROUND_TRIP"
}
}
You can simply make a JSON format like this.
const dummyObject = {
name: 'Dummy',
age: 22,
about: {
hobbies: ['soccer']
},
works: true
}

Filter JSON object

i would like to ask how i can achieve a result what i want i tried in different ways but i couldn't do, this is the json
[
[
{
"id": "2059623",
"name": "England-Belgium",
"tournament_stageFK": "841049",
"startdate": "2018/06/28 18:00:00",
"status_type": "Not started",
"status_descFK": "1",
"n": "4",
"ut": "2018/06/27 12:31:39",
"tournamentFK": "9731",
"tournament_templateFK": "77",
"sportFK": "1",
"tournament_stage_name": "World Cup Grp. G",
"tournament_name": "2018",
"tournament_template_name": "World Cup",
"sport_name": "Football",
},
{
"id": "2059624",
"name": "Panama-Tunisia",
"tournament_stageFK": "841049",
"startdate": "2018/06/28 18:00:00",
"status_type": "Not started",
"status_descFK": "1",
"n": "7",
"ut": "2018/06/27 12:34:01",
"tournamentFK": "9731",
"tournament_templateFK": "77",
"sportFK": "1",
"tournament_stage_name": "World Cup Grp. G",
"tournament_name": "2018",
"tournament_template_name": "World Cup",
"sport_name": "Football",
},
],
[
{
"id": "2681772",
"name": "Piteaa IF-Vittsjoe GIK",
"tournament_stageFK": "853166",
"startdate": "2018/06/28 17:00:00",
"status_type": "Not started",
"status_descFK": "1",
"n": "1",
"ut": "2017/12/18 15:02:33",
"tournamentFK": "12327",
"tournament_templateFK": "9089",
"sportFK": "1",
"tournament_stage_name": "Damallsvenskan",
"tournament_name": "2018",
"tournament_template_name": "Damallsvenskan",
"sport_name": "Football",
}
],
[
{
"id": "2705231",
"name": "Ifoe Bromoella IF-IFK Haessleholm",
"tournament_stageFK": "853950",
"startdate": "2018/06/28 17:00:00",
"status_type": "Not started",
"status_descFK": "1",
"n": "1",
"ut": "2018/02/12 13:02:19",
"tournamentFK": "12458",
"tournament_templateFK": "170",
"sportFK": "1",
"tournament_stage_name": "2. Division Ostra Gotaland",
"tournament_name": "2018",
"tournament_template_name": "2. Division",
"sport_name": "Football",
}
]
]
if you look closer you will notice that games are grouped by tournamentFK this is good now what i want is to clear a little bit this JSON the result that i want it is like this:
{
"competitionId": "456789",
"competitionName": "World Cup 2018",
"matches":[
{
"matchId":1234,
"teamA":"England",
"teamB":"Poland",
"time":"05:00",
"result":"3-3"
"stadium":"somewhere",
"halfTimeScore":"1-2"
},
{
"matchId":9876,
"teamA":"Spain",
"teamB":"Morocco",
"time":"05:00",
"result":"3-3"
"stadium":"somewhere",
"halfTimeScore":"2-1"
}
]
}
i need to get only one time tournamentFK and tournament_template_name and then to loop inside for each tournament and to make one clearly object.
my code:
fixturesTofilter.forEach((fixture) => {
sameGroup.push(fixture.tournamentFK);
competitionName.push(fixture.tournament_template_name);
});
const groupByTournament = sameGroup.filter((item, pos) => sameGroup.indexOf(item) === pos);
const clearSameCompetition = competitionName.filter((item, pos) => competitionName.indexOf(item) === pos);
// console.log(clearSameCompetition);
groupByTournament.forEach((byTournamentFk, index) => {
const grouped = groupBy(fixturesTofilter, item => item.tournamentFK);
groupedFixtures.push(grouped.get(byTournamentFk));
});
console.log(groupedFixtures);
You can easily flatten this object via lodash. Since the JSON object is flatterned, you can just add the tournamentFK and tournament_template_name. Hope this is what you are looking for.
const _ = require('lodash');
const obj = [
[
{
"id": "2059623",
"name": "England-Belgium",
"tournament_stageFK": "841049",
"startdate": "2018/06/28 18:00:00",
"status_type": "Not started",
"status_descFK": "1",
"n": "4",
"ut": "2018/06/27 12:31:39",
"tournamentFK": "9731",
"tournament_templateFK": "77",
"sportFK": "1",
"tournament_stage_name": "World Cup Grp. G",
"tournament_name": "2018",
"tournament_template_name": "World Cup",
"sport_name": "Football"
},
{
"id": "2059624",
"name": "Panama-Tunisia",
"tournament_stageFK": "841049",
"startdate": "2018/06/28 18:00:00",
"status_type": "Not started",
"status_descFK": "1",
"n": "7",
"ut": "2018/06/27 12:34:01",
"tournamentFK": "9731",
"tournament_templateFK": "77",
"sportFK": "1",
"tournament_stage_name": "World Cup Grp. G",
"tournament_name": "2018",
"tournament_template_name": "World Cup",
"sport_name": "Football"
}
],
[
{
"id": "2681772",
"name": "Piteaa IF-Vittsjoe GIK",
"tournament_stageFK": "853166",
"startdate": "2018/06/28 17:00:00",
"status_type": "Not started",
"status_descFK": "1",
"n": "1",
"ut": "2017/12/18 15:02:33",
"tournamentFK": "12327",
"tournament_templateFK": "9089",
"sportFK": "1",
"tournament_stage_name": "Damallsvenskan",
"tournament_name": "2018",
"tournament_template_name": "Damallsvenskan",
"sport_name": "Football"
}
],
[
{
"id": "2705231",
"name": "Ifoe Bromoella IF-IFK Haessleholm",
"tournament_stageFK": "853950",
"startdate": "2018/06/28 17:00:00",
"status_type": "Not started",
"status_descFK": "1",
"n": "1",
"ut": "2018/02/12 13:02:19",
"tournamentFK": "12458",
"tournament_templateFK": "170",
"sportFK": "1",
"tournament_stage_name": "2. Division Ostra Gotaland",
"tournament_name": "2018",
"tournament_template_name": "2. Division",
"sport_name": "Football"
}
]
]
const formatted = _.flattenDeep(obj)
const res = formatted.map(item => {
const newObj = {
matchId: item.tournamentFK,
teamA: item.name.split("-")[0],
teamB: item.name.split("-")[1],
time: item.startdate,
result:"how ??",
stadium:"somewhere",
halfTimeScore:"How?"
}
return newObj
})
console.log(res)

Not able to fetch Weather Data from the Json Data using Angular

Is the parsing way wrong? I'm trying to get weather data
function Hello($scope, $http) {
$http
.jsonp('http://api.worldweatheronline.com/free/v1/weather.ashx?q=London&format=json&num_of_days=5&key=MYKEY&callback=JSON_CALLBACK')
.success(function(data) {
var datais = JSON.stringify(data);
console.log("Datais::"+datais);
console.log("Weather::"+datais["weather"]);
})
.error(function(data){
alert("Error");
});
}
Output:
Datais::{
"data": {
"current_condition": [{
"cloudcover": "25",
"humidity": "76",
"observation_time": "09:13 AM",
"precipMM": "0.0",
"pressure": "992",
"temp_C": "9",
"temp_F": "48",
"visibility": "10",
"weatherCode": "113",
"weatherDesc": [{
"value": "Sunny"
}],
"weatherIconUrl": [{
"value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0001_sunny.png"
}],
"winddir16Point": "SSW",
"winddirDegree": "200",
"windspeedKmph": "13",
"windspeedMiles": "8"
}],
"request": [{
"query": "London, United Kingdom",
"type": "City"
}],
"weather": [{
"date": "2014-01-16",
"precipMM": "1.6",
"tempMaxC": "11",
"tempMaxF": "52",
"tempMinC": "5",
"tempMinF": "41",
"weatherCode": "116",
"weatherDesc": [{
"value": "Partly Cloudy"
}],
"weatherIconUrl": [{
"value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png"
}],
"winddir16Point": "S",
"winddirDegree": "191",
"winddirection": "S",
"windspeedKmph": "30",
"windspeedMiles": "19"
}, {
"date": "2014-01-17",
"precipMM": "1.3",
"tempMaxC": "10",
"tempMaxF": "50",
"tempMinC": "5",
"tempMinF": "42",
"weatherCode": "116",
"weatherDesc": [{
"value": "Partly Cloudy"
}],
"weatherIconUrl": [{
"value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png"
}],
"winddir16Point": "SSW",
"winddirDegree": "202",
"winddirection": "SSW",
"windspeedKmph": "27",
"windspeedMiles": "17"
}, {
"date": "2014-01-18",
"precipMM": "2.7",
"tempMaxC": "10",
"tempMaxF": "49",
"tempMinC": "4",
"tempMinF": "39",
"weatherCode": "266",
"weatherDesc": [{
"value": "Light drizzle"
}],
"weatherIconUrl": [{
"value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0017_cloudy_with_light_rain.png"
}],
"winddir16Point": "S",
"winddirDegree": "177",
"winddirection": "S",
"windspeedKmph": "23",
"windspeedMiles": "15"
}, {
"date": "2014-01-19",
"precipMM": "1.0",
"tempMaxC": "8",
"tempMaxF": "46",
"tempMinC": "5",
"tempMinF": "41",
"weatherCode": "122",
"weatherDesc": [{
"value": "Overcast"
}],
"weatherIconUrl": [{
"value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0004_black_low_cloud.png"
}],
"winddir16Point": "ESE",
"winddirDegree": "110",
"winddirection": "ESE",
"windspeedKmph": "13",
"windspeedMiles": "8"
}, {
"date": "2014-01-20",
"precipMM": "0.4",
"tempMaxC": "8",
"tempMaxF": "47",
"tempMinC": "1",
"tempMinF": "34",
"weatherCode": "116",
"weatherDesc": [{
"value": "Partly Cloudy"
}],
"weatherIconUrl": [{
"value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png"
}],
"winddir16Point": "NW",
"winddirDegree": "311",
"winddirection": "NW",
"windspeedKmph": "12",
"windspeedMiles": "7"
}]
}
}
Weather::undefined
Here your datais variable is assigned the data.
if you inspect properly the json data returned as you can see in your console.log(datais);
you will be able to access weather property in datais.data.weather.
try this
console.log("Weather::"+datais.data.weather);
You will be able to access weather property.
Further weather property is an array which has weather values from today up to 4 upcoming days. you can access them in a loop
for(i=0; i<datais.data.weather.length; i++){
console.log(datais.data.weather[i]);
}
Or for example access todays weather data:
console.log(datais.data.weather[0].date);
console.log(datais.data.weather[0].tempMaxC);
console.log(datais.data.weather[0].tempMinC);
i htink you need to access the weather this way:
console.log("Weather::"+datais.data.weather);
you may use an onlne json viewer to view the structure of your data: for example: http://jsonviewer.stack.hu/ or take at look at the browser console. firebug, for example, can show the json data as tree.
And you don't need JSON.stringify. Angular does this for you:
.success(function(data) {
console.log(data.data.weather);
})

How to determine if an identifier needs to be delimited in T-SQL?

A lot (all?) of SQL Server tools generate T-SQL quote and uniformly quote/delimit all identifiers. This is understandable, as an arbitrary identifier may need to be quoted. However, the generated code is less readable and a large number of identifiers actually in use don't need to be quoted.
I'm curious if there is a solution in any language that could be used to selectively quote only those identifiers that require it (to be used in T-SQL with valid syntax).
For SQL Server 2008 R2, based on the reserved keywords (including the ODBC and future reserved keywords) and the rules for regular identifiers, here's some example LINQPad code (for a "C# Program" query) to determine whether identifiers need to be delimited (i.e. aren't 'regular' identifiers):
void Main()
{
TestIfIdentifierIsRegular("Description");
TestIfIdentifierIsRegular("This should not be considered regular");
TestIfIdentifierIsRegular("EntityId");
TestIfIdentifierIsRegular("Jānis_Bērziņš");
}
void TestIfIdentifierIsRegular(string identifier)
{
String.Format("\"{0}\" is regular? {1}", identifier, IsIdentifierRegular(identifier)).Dump();
}
bool IsIdentifierRegular(string identifier)
{
List<string> reservedKeywords = new List<string> { "ADD", "ALL", "ALTER", "AND", "ANY", "AS", "ASC", "AUTHORIZATION", "BACKUP", "BEGIN", "BETWEEN", "BREAK", "BROWSE", "BULK", "BY", "CASCADE", "CASE", "CHECK", "CHECKPOINT", "CLOSE", "CLUSTERED", "COALESCE", "COLLATE", "COLUMN", "COMMIT", "COMPUTE", "CONSTRAINT", "CONTAINS", "CONTAINSTABLE", "CONTINUE", "CONVERT", "CREATE", "CROSS", "CURRENT", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR", "DATABASE", "DBCC", "DEALLOCATE", "DECLARE", "DEFAULT", "DELETE", "DENY", "DESC", "DISK", "DISTINCT", "DISTRIBUTED", "DOUBLE", "DROP", "DUMP", "ELSE", "END", "ERRLVL", "ESCAPE", "EXCEPT", "EXEC", "EXECUTE", "EXISTS", "EXIT", "EXTERNAL", "FETCH", "FILE", "FILLFACTOR", "FOR", "FOREIGN", "FREETEXT", "FREETEXTTABLE", "FROM", "FULL", "FUNCTION", "GOTO", "GRANT", "GROUP", "HAVING", "HOLDLOCK", "IDENTITY", "IDENTITY_INSERT", "IDENTITYCOL", "IF", "IN", "INDEX", "INNER", "INSERT", "INTERSECT", "INTO", "IS", "JOIN", "KEY", "KILL", "LEFT", "LIKE", "LINENO", "LOAD", "MERGE", "NATIONAL", "NOCHECK", "NONCLUSTERED", "NOT", "NULL", "NULLIF", "OF", "OFF", "OFFSETS", "ON", "OPEN", "OPENDATASOURCE", "OPENQUERY", "OPENROWSET", "OPENXML", "OPTION", "OR", "ORDER", "OUTER", "OVER", "PERCENT", "PIVOT", "PLAN", "PRECISION", "PRIMARY", "PRINT", "PROC", "PROCEDURE", "PUBLIC", "RAISERROR", "READ", "READTEXT", "RECONFIGURE", "REFERENCES", "REPLICATION", "RESTORE", "RESTRICT", "RETURN", "REVERT", "REVOKE", "RIGHT", "ROLLBACK", "ROWCOUNT", "ROWGUIDCOL", "RULE", "SAVE", "SCHEMA", "SECURITYAUDIT", "SELECT", "SESSION_USER", "SET", "SETUSER", "SHUTDOWN", "SOME", "STATISTICS", "SYSTEM_USER", "TABLE", "TABLESAMPLE", "TEXTSIZE", "THEN", "TO", "TOP", "TRAN", "TRANSACTION", "TRIGGER", "TRUNCATE", "TSEQUAL", "UNION", "UNIQUE", "UNPIVOT", "UPDATE", "UPDATETEXT", "USE", "USER", "VALUES", "VARYING", "VIEW", "WAITFOR", "WHEN", "WHERE", "WHILE", "WITH", "WRITETEXT", "ABSOLUTE", "ACTION", "ADA", "ADD", "ALL", "ALLOCATE", "ALTER", "AND", "ANY", "ARE", "AS", "ASC", "ASSERTION", "AT", "AUTHORIZATION", "AVG", "BEGIN", "BETWEEN", "BIT", "BIT_LENGTH", "BOTH", "BY", "CASCADE", "CASCADED", "CASE", "CAST", "CATALOG", "CHAR", "CHAR_LENGTH", "CHARACTER", "CHARACTER_LENGTH", "CHECK", "CLOSE", "COALESCE", "COLLATE", "COLLATION", "COLUMN", "COMMIT", "CONNECT", "CONNECTION", "CONSTRAINT", "CONSTRAINTS", "CONTINUE", "CONVERT", "CORRESPONDING", "COUNT", "CREATE", "CROSS", "CURRENT", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR", "DATE", "DAY", "DEALLOCATE", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DEFERRABLE", "DEFERRED", "DELETE", "DESC", "DESCRIBE", "DESCRIPTOR", "DIAGNOSTICS", "DISCONNECT", "DISTINCT", "DOMAIN", "DOUBLE", "DROP", "ELSE", "END", "END-EXEC", "ESCAPE", "EXCEPT", "EXCEPTION", "EXEC", "EXECUTE", "EXISTS", "EXTERNAL", "EXTRACT", "FALSE", "FETCH", "FIRST", "FLOAT", "FOR", "FOREIGN", "FORTRAN", "FOUND", "FROM", "FULL", "GET", "GLOBAL", "GO", "GOTO", "GRANT", "GROUP", "HAVING", "HOUR", "IDENTITY", "IMMEDIATE", "IN", "INCLUDE", "INDEX", "INDICATOR", "INITIALLY", "INNER", "INPUT", "INSENSITIVE", "INSERT", "INT", "INTEGER", "INTERSECT", "INTERVAL", "INTO", "IS", "ISOLATION", "JOIN", "KEY", "LANGUAGE", "LAST", "LEADING", "LEFT", "LEVEL", "LIKE", "LOCAL", "LOWER", "MATCH", "MAX", "MIN", "MINUTE", "MODULE", "MONTH", "NAMES", "NATIONAL", "NATURAL", "NCHAR", "NEXT", "NO", "NONE", "NOT", "NULL", "NULLIF", "NUMERIC", "OCTET_LENGTH", "OF", "ON", "ONLY", "OPEN", "OPTION", "OR", "ORDER", "OUTER", "OUTPUT", "OVERLAPS", "PAD", "PARTIAL", "PASCAL", "POSITION", "PRECISION", "PREPARE", "PRESERVE", "PRIMARY", "PRIOR", "PRIVILEGES", "PROCEDURE", "PUBLIC", "READ", "REAL", "REFERENCES", "RELATIVE", "RESTRICT", "REVOKE", "RIGHT", "ROLLBACK", "ROWS", "SCHEMA", "SCROLL", "SECOND", "SECTION", "SELECT", "SESSION", "SESSION_USER", "SET", "SIZE", "SMALLINT", "SOME", "SPACE", "SQL", "SQLCA", "SQLCODE", "SQLERROR", "SQLSTATE", "SQLWARNING", "SUBSTRING", "SUM", "SYSTEM_USER", "TABLE", "TEMPORARY", "THEN", "TIME", "TIMESTAMP", "TIMEZONE_HOUR", "TIMEZONE_MINUTE", "TO", "TRAILING", "TRANSACTION", "TRANSLATE", "TRANSLATION", "TRIM", "TRUE", "UNION", "UNIQUE", "UNKNOWN", "UPDATE", "UPPER", "USAGE", "USER", "USING", "VALUE", "VALUES", "VARCHAR", "VARYING", "VIEW", "WHEN", "WHENEVER", "WHERE", "WITH", "WORK", "WRITE", "YEAR", "ZONE", "ABSOLUTE", "ACTION", "ADMIN", "AFTER", "AGGREGATE", "ALIAS", "ALLOCATE", "ARE", "ARRAY", "ASENSITIVE", "ASSERTION", "ASYMMETRIC", "AT", "ATOMIC", "BEFORE", "BINARY", "BIT", "BLOB", "BOOLEAN", "BOTH", "BREADTH", "CALL", "CALLED", "CARDINALITY", "CASCADED", "CAST", "CATALOG", "CHAR", "CHARACTER", "CLASS", "CLOB", "COLLATION", "COLLECT", "COMPLETION", "CONDITION", "CONNECT", "CONNECTION", "CONSTRAINTS", "CONSTRUCTOR", "CORR", "CORRESPONDING", "COVAR_POP", "COVAR_SAMP", "CUBE", "CUME_DIST", "CURRENT_CATALOG", "CURRENT_DEFAULT_TRANSFORM_GROUP", "CURRENT_PATH", "CURRENT_ROLE", "CURRENT_SCHEMA", "CURRENT_TRANSFORM_GROUP_FOR_TYPE", "CYCLE", "DATA", "DATE", "DAY", "DEC", "DECIMAL", "DEFERRABLE", "DEFERRED", "DEPTH", "DEREF", "DESCRIBE", "DESCRIPTOR", "DESTROY", "DESTRUCTOR", "DETERMINISTIC", "DICTIONARY", "DIAGNOSTICS", "DISCONNECT", "DOMAIN", "DYNAMIC", "EACH", "ELEMENT", "END-EXEC", "EQUALS", "EVERY", "EXCEPTION", "FALSE", "FILTER", "FIRST", "FLOAT", "FOUND", "FREE", "FULLTEXTTABLE", "FUSION", "GENERAL", "GET", "GLOBAL", "GO", "GROUPING", "HOLD", "HOST", "HOUR", "IGNORE", "IMMEDIATE", "INDICATOR", "INITIALIZE", "INITIALLY", "INOUT", "INPUT", "INT", "INTEGER", "INTERSECTION", "INTERVAL", "ISOLATION", "ITERATE", "LANGUAGE", "LARGE", "LAST", "LATERAL", "LEADING", "LESS", "LEVEL", "LIKE_REGEX", "LIMIT", "LN", "LOCAL", "LOCALTIME", "LOCALTIMESTAMP", "LOCATOR", "MAP", "MATCH", "MEMBER", "METHOD", "MINUTE", "MOD", "MODIFIES", "MODIFY", "MODULE", "MONTH", "MULTISET", "NAMES", "NATURAL", "NCHAR", "NCLOB", "NEW", "NEXT", "NO", "NONE", "NORMALIZE", "NUMERIC", "OBJECT", "OCCURRENCES_REGEX", "OLD", "ONLY", "OPERATION", "ORDINALITY", "OUT", "OVERLAY", "OUTPUT", "PAD", "PARAMETER", "PARAMETERS", "PARTIAL", "PARTITION", "PATH", "POSTFIX", "PREFIX", "PREORDER", "PREPARE", "PERCENT_RANK", "PERCENTILE_CONT", "PERCENTILE_DISC", "POSITION_REGEX", "PRESERVE", "PRIOR", "PRIVILEGES", "RANGE", "READS", "REAL", "RECURSIVE", "REF", "REFERENCING", "REGR_AVGX", "REGR_AVGY", "REGR_COUNT", "REGR_INTERCEPT", "REGR_R2", "REGR_SLOPE", "REGR_SXX", "REGR_SXY", "REGR_SYY", "RELATIVE", "RELEASE", "RESULT", "RETURNS", "ROLE", "ROLLUP", "ROUTINE", "ROW", "ROWS", "SAVEPOINT", "SCROLL", "SCOPE", "SEARCH", "SECOND", "SECTION", "SENSITIVE", "SEQUENCE", "SESSION", "SETS", "SIMILAR", "SIZE", "SMALLINT", "SPACE", "SPECIFIC", "SPECIFICTYPE", "SQL", "SQLEXCEPTION", "SQLSTATE", "SQLWARNING", "START", "STATE", "STATEMENT", "STATIC", "STDDEV_POP", "STDDEV_SAMP", "STRUCTURE", "SUBMULTISET", "SUBSTRING_REGEX", "SYMMETRIC", "SYSTEM", "TEMPORARY", "TERMINATE", "THAN", "TIME", "TIMESTAMP", "TIMEZONE_HOUR", "TIMEZONE_MINUTE", "TRAILING", "TRANSLATE_REGEX", "TRANSLATION", "TREAT", "TRUE", "UESCAPE", "UNDER", "UNKNOWN", "UNNEST", "USAGE", "USING", "VALUE", "VAR_POP", "VAR_SAMP", "VARCHAR", "VARIABLE", "WHENEVER", "WIDTH_BUCKET", "WITHOUT", "WINDOW", "WITHIN", "WORK", "WRITE", "XMLAGG", "XMLATTRIBUTES", "XMLBINARY", "XMLCAST", "XMLCOMMENT", "XMLCONCAT", "XMLDOCUMENT", "XMLELEMENT", "XMLEXISTS", "XMLFOREST", "XMLITERATE", "XMLNAMESPACES", "XMLPARSE", "XMLPI", "XMLQUERY", "XMLSERIALIZE", "XMLTABLE", "XMLTEXT", "XMLVALIDATE", "YEAR", "ZONE" };
if (reservedKeywords.Contains(identifier.ToUpper()))
return false;
Regex regularIdentifierRegex = new Regex(#"^[\p{L}_][\p{L}\p{N}#$#_]*$");
Match match = regularIdentifierRegex.Match(identifier);
return match.Success;
}
The output of running the above code as a LINQPad query:
"Description" is regular? True
"This should not be considered regular" is regular? False
"EntityId" is regular? True
"Jānis_Bērziņš" is regular? True

Resources