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

如何使用JSONata将字符串数组转换为带行号属性的对象数组?

How to Add Dynamic Line Numbers for Variable-Length Arrays in JSONata

Got it, I know exactly how to fix this for you! The key here is using JSONata's built-in index tracking when iterating over arrays—you don't have to hardcode line numbers, even if the array length changes.

The Correct Expression

Instead of your current approach, use either of these two methods to dynamically grab the element's index and set the line value correctly:

Method 1: Using Array Iteration with $index

You can directly iterate over the Street array and access the current element's index with $index (note: it starts at 0, so we add 1 to get the 1-based line number):

Street @ $index.{
  "attributes": {"line": $index + 1},
  "text": $
}

Method 2: Using $map() Function (More Explicit)

If you prefer a more functional style, the $map() function lets you explicitly pass both the value and index of each element:

$map(Street, function($value, $idx) {
  {
    "attributes": {"line": $idx + 1},
    "text": $value
  }
})

How It Works

  • Both methods will loop through every element in your Street array, no matter how long it gets.
  • $index (in method 1) or $idx (in method 2) gives you the zero-based position of the current element. Adding 1 converts it to the 1-based line number you need.
  • The output will automatically match your desired format: for each string in the input array, you'll get an object with the correct line number and the original text.

Example Test

If you input:

{ "Street": ["10 First Avenue","Third Floor"] }

Either expression will output:

[
  {
    "attributes": {"line": 1},
    "text": "10 First Avenue"
  },
  {
    "attributes": {"line": 2},
    "text": "Third Floor"
  }
]

And if you add more elements to the Street array later, like ["10 First Avenue","Third Floor","Apt 4B"], it will automatically generate a line: 3 entry for the new element—no changes to the expression needed!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 21:59:08