如何使用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
Streetarray, 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
linenumber 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

