我开发了一个 API 作为销售点网站的后端。 网站将 JSON 传递到 API 端点。 在网站上,用户将商品添加到购物车后,点击“结帐”。网站调用 API 端点 CheckOut()。该网站必须传递具有我所说的 2 个节点“购买”和“订单项”的 JSON。我的 Web 开发人员告诉我,他不知道如何发送 JSON 的“lineitems”部分。我相信我的答案应该是,“好吧,你需要学习如何将购物车数组添加到 JSON”,但我的 Web 开发人员非常有经验,所以我想知道我是否误解了。我的问题:如何将 lineitems 数组添加到将传递到 API 端点 CheckOut() 的 JSON 中?我不是网络开发人员,所以我想我只需要大局观或告诉我的网络开发人员阅读/谷歌的内容。这是我的端点期望的 JSON:
{
"purchase": {
"citf": "LPSO",
"citfuserid": "2314734",
"citfsessiontoken": "A6BBB754BD9F4EB9",
"ytotal_sale": 20.70,
"ytotal_tax": 1.08
},
"lineitems": [
{
"cpl_dscs_id": "0142C45AFF0A4C89",
"nqty": 8,
"yunit_price": 1.35,
"ntax_rate": 8.45
},
{
"cpl_dscs_id": "034CA60B26FD4C8A",
"nqty": 1,
"yunit_price": 32.89,
"ntax_rate": 8.45
},
{
"cpl_dscs_id": "03605BACB1364791",
"nqty": 5,
"yunit_price": 3.32,
"ntax_rate": 8.45
},
{
"cpl_dscs_id": "037FB5C58F8849B2",
"nqty": 3,
"yunit_price": 6.04,
"ntax_rate": 4
},
{
"cpl_dscs_id": "0B81210989A649AC",
"nqty": 1,
"yunit_price": 4.03,
"ntax_rate": 4
}
]
}
谢谢, 约翰
网站必须传递具有我所说的 2 个节点“购买”和“订单项”的 JSON
用技术术语来说,你所说的“2个节点”实际上是一个对象(购买)和一个对象数组(行项目)。所以我会按照以下步骤操作:
对于第 1 点),假设您使用的是 Javascript(您可以使用 both Javascript 和 Typescript 与 React),我会尝试以下操作:
// Assuming you have an array of line items
var lineItems = [
{
"cpl_dscs_id": "0142C45AFF0A4C89",
"nqty": 8,
"yunit_price": 1.35,
"ntax_rate": 8.45
},
{
"cpl_dscs_id": "034CA60B26FD4C8A",
"nqty": 1,
"yunit_price": 32.89,
"ntax_rate": 8.45
},
// ...and more line items
];
// Construct the purchase object
var purchase = {
"citf": "LPSO",
"citfuserid": "2314734",
"citfsessiontoken": "A6BBB754BD9F4EB9",
"ytotal_sale": 20.70,
"ytotal_tax": 1.08
};
// Combine purchase and line items into a single object
var data = {
"purchase": purchase,
"lineitems": lineItems
};
// Convert the data object to JSON string
var jsonData = JSON.stringify(data);
至于第 2)点,这实际上取决于您的代码库如何处理事情。假设你正在使用 ReactJS,你可能会被赋予这篇文章的标签,我可以想象一个类似于以下的解决方案,全部包括:
import React, { useState } from 'react';
const CheckoutComponent = () => {
// State to hold line items and purchase data
const [lineItems, setLineItems] = useState([
// Your line items array here
]);
const [purchase, setPurchase] = useState({
citf: 'LPSO',
citfuserid: '2314734',
citfsessiontoken: 'A6BBB754BD9F4EB9',
ytotal_sale: 20.70,
ytotal_tax: 1.08,
});
// Function to handle checkout
const handleCheckout = () => {
// Combine line items and purchase into a single object
const data = {
purchase: purchase,
lineitems: lineItems,
};
// Convert the data object to JSON string
const jsonData = JSON.stringify(data);
// Make API call to your endpoint
fetch('your-api-endpoint-url', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: jsonData,
})
.then(response => response.json())
.then(data => {
// Handle response from the server
console.log(data);
})
.catch(error => {
// Handle error
console.error('Error:', error);
});
};
return (
<div>
{/* Your component JSX here */}
<button onClick={handleCheckout}>Checkout</button>
</div>
);
};
export default CheckoutComponent;