Skip to content

parseAsType API gives an error for valid Json value while converting to an expected type #2560

@SasinduDilshara

Description

@SasinduDilshara

Problem

The following code gives the following error

import ballerina/data.jsondata;
import ballerina/io;
json v = {
  "id": "xxx",
  "object": "response",
  "created_at": 1771847449,
  "status": "completed",
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1771847494,
  "error": null,
  "frequency_penalty": 0.0,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 16384,
  "max_tool_calls": null,
  "model": "gpt-5-mini-2025-08-07",
  "output": [
    {
      "id": "xxx",
      "type": "reasoning",
      "summary": []
    },
    {
      "id": "xxx",
      "type": "code_interpreter_call",
      "status": "completed",
      "code": "# The following string contains the Python code used for all steps.\n# We'll print the code first, then execute it so you can see both the code and the results.\n\ncode = r\"\"\"\n# 1. Generate the first 30 Fibonacci numbers (using F1 = 1, F2 = 1)\ndef generate_fibonacci(n):\n    if n <= 0:\n        return []\n    if n == 1:\n        return [1]\n    fibs = [1, 1]\n    for _ in range(2, n):\n        fibs.append(fibs[-1] + fibs[-2])\n    return fibs\n\n# 2. For each consecutive pair, calculate their ratio and compare to phi\nfrom math import sqrt\n\nphi = (1 + sqrt(5)) / 2\n\n# 3. Primality test for small integers\ndef is_prime(num):\n    if num <= 1:\n        return False\n    if num <= 3:\n        return True\n    if num % 2 == 0:\n        return False\n    r = int(num**0.5)\n    for i in range(3, r+1, 2):\n        if num % i == 0:\n            return False\n    return True\n\n# 4. Sum of even Fibonacci numbers among the first n\ndef sum_even_fibs(fibs):\n    return sum(x for x in fibs if x % 2 == 0)\n\n# 5. Verify identity: sum of first n Fibonacci numbers = F(n+2) - 1\n# (Using 1-indexed F1=1... so F(n+2) corresponds to fibs[n+1] in 0-indexed list)\n\n# Generate first 30 Fibonacci numbers\nn_total = 30\nfibs = generate_fibonacci(n_total)\n\n# Display results\nprint(\"1) First 30 Fibonacci numbers (F1 = 1, F2 = 1):\")\nprint(fibs)\nprint()\n\n# Ratios and convergence to phi\nprint(\"2) Ratios F(n+1)/F(n) for n = 1..29 and difference to phi:\")\nprint(f\"{'n':>2} {'F(n)':>10} {'F(n+1)':>10} {'Ratio':>18} {'|Ratio - phi|':>18}\")\nfor i in range(len(fibs)-1):\n    a = fibs[i]\n    b = fibs[i+1]\n    ratio = b / a\n    diff = abs(ratio - phi)\n    print(f\"{i+1:2d} {a:10d} {b:10d} {ratio:18.12f} {diff:18.12f}\")\nprint()\nprint(f\"Reference phi = (1 + sqrt(5)) / 2 = {phi:.12f}\")\nprint()\n\n# Prime Fibonacci numbers among first 30\nprime_fibs = [x for x in fibs if is_prime(x)]\nprint(\"3) Fibonacci numbers among the first 30 that are prime:\")\nprint(prime_fibs)\nprint()\n\n# Sum of even Fibonacci numbers in the first 30\nsum_even = sum_even_fibs(fibs)\nprint(\"4) Sum of all even Fibonacci numbers among the first 30:\")\nprint(sum_even)\nprint()\n\n# 5) Verify identity for n = 10, 20, 30\nprint(\"5) Verify sum_{k=1..n} F(k) = F(n+2) - 1 for n = 10, 20, 30\")\nfor n in [10, 20, 30]:\n    sum_first_n = sum(fibs[:n])\n    # F(n+2) is fibs[n+1] (0-indexed)\n    fnp2 = generate_fibonacci(n+2)[-1]  # safe way to get F(n+2)\n    rhs = fnp2 - 1\n    holds = (sum_first_n == rhs)\n    print(f\"n = {n}: sum(F1..F{n}) = {sum_first_n}, F({n+2}) - 1 = {rhs} -> holds: {holds}\")\n\"\"\"\n\nprint(\"=== Python code used ===\")\nprint(code)\nprint(\"=== Output ===\")\nexec(code)",
      "container_id": "cntr_699c3f1d93d08190aa2505fbdd08e00909b7a43cf5b4fc32",
      "outputs": null
    },
    {
      "id": "xxx",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [],
          "logprobs": [],
          "text": "I ran the Python code (shown above) and produced the requested calculations. Summary of the results:\n\n- Definition used: Fibonacci sequence with F1 = 1, F2 = 1 (so the list begins 1, 1, 2, 3, ...).\n\n1) First 30 Fibonacci numbers:\n[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040]\n\n2) Ratios F(n+1)/F(n) and convergence to phi:\nI printed the ratio for n = 1..29 (showing F(n), F(n+1), the ratio, and |ratio - phi|). The ratios converge to phi = (1 + sqrt(5)) / 2 ≈ 1.618033988750. Example values (ratio, |difference|):\n- n=1: ratio = 1.000000000000, |diff| = 0.618033988750\n- n=5: ratio = 1.600000000000, |diff| = 0.018033988750\n- n=10: ratio = 1.618181818182, |diff| = 0.000147829432\n- n=20: ratio = 1.618033998522, |diff| = 0.000000009772\n- n=29: ratio = 1.618033988748, |diff| = 0.000000000002\n\nThis shows clear convergence toward phi.\n\n3) Fibonacci numbers among the first 30 that are prime:\n[2, 3, 5, 13, 89, 233, 1597, 28657, 514229]\n\n4) Sum of all even Fibonacci numbers in the first 30:\n1089154\n\n5) Verification of the identity sum_{k=1..n} F(k) = F(n+2) - 1 for n = 10, 20, 30:\n- n = 10: sum = 143, F(12) - 1 = 143 -> holds: True\n- n = 20: sum = 17710, F(22) - 1 = 17710 -> holds: True\n- n = 30: sum = 2178308, F(32) - 1 = 2178308 -> holds: True\n\nThe full Python code used and the exact printed outputs are included above. If you want the code saved to a file (e.g., .py) or want me to run variants (different Fibonacci start values, more terms, or additional visualizations), tell me and I'll produce them."
        }
      ],
      "role": "assistant"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0.0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": null,
  "reasoning": {
    "effort": "medium",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": true,
  "temperature": 1.0,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [
    {
      "type": "code_interpreter",
      "container": {
        "type": "auto"
      }
    }
  ],
  "top_logprobs": 0,
  "top_p": 1.0,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 5001,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 2856,
    "output_tokens_details": {
      "reasoning_tokens": 1280
    },
    "total_tokens": 7857
  },
  "user": null,
  "metadata": {}
};

public function main() returns error? {
    Response r = check jsondata:parseAsType(v);
    io:println("Parsed response object: ", r);
}

error: required field 'encrypted_content' not present in JSON

Proposed Solution

Fix the bug in the parseAsType to allow parsing union types

Alternatives

No response

Version

No response

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions