从Javascript中的API调用连接两个不同的JSON对象



我正在研究一个货币转换项目,试图让我的代码从我的网站上的JSON响应显示结果,我还不能做到这一点。下面的代码

.then((response) => {
return response.json();
})
.then((jsonResponse) => {
let objData = {
amount: '',
from: '',
to: '',
result: '',
};
window.console.log('jsonresponse ==>' + JSON.stringify(jsonResponse));
let exchangeData = jsonResponse['query'];
window.console.log('exchangeData==> ' + JSON.stringify(exchangeData))
objData.amount = exchangeData['amount'];
objData.from = exchangeData['from'];
objData.to = exchangeData['to'];
objData.result = exchangeData['result'];
this.conversionData = objData;
window.console.log('objData=' + JSON.stringify(objData));
}).catch(error => {
window.console.log('callout error ' + JSON.stringify(error));
})
}
}

只返回'amount', 'from'和'to'而不返回'result'。如何让它返回转换的结果?这是JSON

示例
{   "info": { "quote": 0.975625, "timestamp": 1669042263 }, 
"query": { "amount": 5, "from": "USD", "to": "EUR" }, 
"result": 4.878125, 
"success": true 
}
现在,我的代码只返回
"query": {
"amount": 5,
"from": "USD",
"to": "EUR"

如何让它返回

"query": {
"amount": 5,
"from": "USD",
"to": "EUR"
"result": 4.878125

我尝试了下面的方法,但是没有成功。

const obj1={"query":[ { "amount":"", "from": "", "to": "" }, ] }; 
const obj2={"result":{}, }; 
const response = JSON.parse(JSON.stringify(obj1)); 
response.query.push(...obj2.result); console.log(response);

你问错地方了

objData.result = exchangeData['result'];

,

let exchangeData = jsonResponse['query'];

jsonResponse['query']不包含result.

你应该做

objData.result = jsonResponse['result'];

最新更新