Copy link to clipboard
Copied
Hi,
The JSON format I would like to send is like this:
{"InvoiceID": "12345",
"InvoiceLine": [{"Description": "Item1", "Quantity": 1, "LineTotal": 20} ,
{"Description": "Item2", "Quantity": 2, "LineTotal": 15} ]
}
I tried to create the above by
<cfset LineInfo =' {"Description": "Item1", "Quantity": 1, "LineTotal": 20} ,
{"Description": "Item2", "Quantity": 2, "LineTotal": 15} '>
This is done after some looping to find out the number of lines I have.
<cfscript>
myStruct=
{"InvoiceID": "12345",
"InvoiceLine": [#LineInfo#]
}
</cfscript>
Then, #serialize JSON(myStruct)# becomes
{"InvoiceID": "12345", "InvoiceLine": ["{\"Description\": \"Item1\", \"Quantity\": 1, \"LineTotal\": 20} ,
{\"Description\": \"Item2\", \"Quantity\": 2, \"LineTotal\": 15} "]}
The problem seems to be the double quotation after [ and before ], or before and after #LineInfo# as above.
Question is how can I generate the nested JSON format I need? I need to do a looop of some sort to find out how many Lines I have.
Any insights?
Thanks!
Dchan
#JSON #CF2016
A slight amendment to my proposal, try the following:
<cfset LineInfo = [{"Description": "Item1", "Quantity": 1, "LineTotal": 20} ,
{"Description": "Item2", "Quantity": 2, "LineTotal": 15}]>
<cfscript>
myStruct=
{"InvoiceID": "12345",
"InvoiceLine": #LineInfo#
}
writeOutput(serializeJSON(myStruct));
</cfscript>
Copy link to clipboard
Copied
The way you have coded this, LineInfo is a string, so InvoiceLine is becoming an array with a single string element.
Change LineInfo into a struct and then the value you assign to InvoiceLine should be [#duplicate(LineInfo)#]
Copy link to clipboard
Copied
A slight amendment to my proposal, try the following:
<cfset LineInfo = [{"Description": "Item1", "Quantity": 1, "LineTotal": 20} ,
{"Description": "Item2", "Quantity": 2, "LineTotal": 15}]>
<cfscript>
myStruct=
{"InvoiceID": "12345",
"InvoiceLine": #LineInfo#
}
writeOutput(serializeJSON(myStruct));
</cfscript>
Copy link to clipboard
Copied
Hi EddieLotter,
That is exactly the way to go. To expand on it, I need to create the "InvoiceLine" array within the myStruct through a loop.
So, I put in an empty array at first and then run the loop to expand on the Array.
<cfscript>
MyStruct=
{"InvoiceID": "12345",
"InvoiceLine": [{}]
}
<cfloop index="i" from="1" to="#OutputRow#">
<cfif i GT 1>
<Cfscript>
ArrayAppend(MyStruct.InvoiceLine,{},"true");
</cfscript>
</cfif>
<cfset MyStruct.InvoiceLine[i]['Description'] ="#ItemDesc[i]#">
<cfset MyStruct.InvoiceLine[i]['Quantity'] =#Qty[i]#>
<cfset MyStruct.InvoiceLine[i]['LineTotal'] =#LineTotal[i]#>
</cfloop>
#serializeJSON(MyStruct)# will get to what I needed.
#OutputRow# is the number of lines.
#ItemDesc[i]#, #Qty[i]#, #LineTotal[i]# holds the Description, Qty and LineTotal information for each line.
Thanks.
Dchan