You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用OpenWhisk与JavaScript计算JSON对象元素总和遇0结果问题求助

Fixing Your OpenWhisk JS Action: Calculating JSON Object Sum

Hey there! Let's troubleshoot why your OpenWhisk JavaScript action is returning 0 instead of the correct total (2+56+99+12 = 169) for your input {0: 2, 1: 56, 2: 99, 3:12}.

Common Causes & Fixes

Most likely, the issue comes from either targeting the wrong part of the input object or not properly handling object properties during traversal. Here are the most straightforward solutions:

1. You're Traversing the Wrong Object

OpenWhisk wraps input data differently depending on how you trigger the action:

  • If you pass the JSON directly as action parameters (via CLI or UI), the key-value pairs live in the top-level params object.
  • If you trigger the action via an HTTP request (e.g., API Gateway), the parsed JSON input is usually nested under params.body.

Fix for direct parameter input:

function main(params) {
  let sum = 0;
  // Loop through all own properties of the params object
  for (const key in params) {
    if (params.hasOwnProperty(key)) {
      const value = params[key];
      // Ensure we only add numeric values
      if (typeof value === 'number') {
        sum += value;
      }
    }
  }
  return { totalSum: sum };
}

Fix for HTTP body input:

function main(params) {
  let sum = 0;
  // Fallback to empty object if body doesn't exist
  const inputData = params.body || {};
  
  for (const key in inputData) {
    if (inputData.hasOwnProperty(key)) {
      const value = inputData[key];
      if (typeof value === 'number') {
        sum += value;
      }
    }
  }
  return { totalSum: sum };
}

2. Why Your Original Code Returned 0

The most probable reasons are:

  • You were iterating over an empty or incorrect object (e.g., params instead of params.body), so the loop never added anything to the initial sum = 0.
  • You didn't check for hasOwnProperty, which could lead to iterating over inherited properties (which might have non-numeric or zero values).

Debugging Tip

To confirm exactly what input your action is receiving, add a console log at the start of your function:

function main(params) {
  console.log('Received params:', JSON.stringify(params));
  // Rest of your code...
}

Then check the action logs via the OpenWhisk CLI with wsk activation logs <activation-id> to see the structure of the incoming data.

内容的提问来源于stack exchange,提问作者zak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:35:37