如何用Step Functions的Map函数解析JSON文件内的JSON数组?
问题解决:Step Functions处理嵌套数组JSON文件报错"Attempting to map over non-iterable node"
问题根源
你设置的ItemsPath: "$.users"是作用在**Map步骤的输入(即EventBridge触发事件数据)**上,而非从S3读取的JSON文件内容上。当使用Distributed Map的S3 ItemReader时,若JSON文件是包含数组的对象(而非纯数组),默认会把整个JSON对象当作单个非可迭代项,因此触发报错。
解决方案
修改ASL代码,在ItemReader的ReaderConfig中添加JSONPath参数,指定从S3读取的JSON文件内数组的路径。同时移除Map层级的ItemsPath配置。
修改后的完整ASL代码
{ "Comment": "A description of my state machine", "StartAt": "Json File Analysis", "States": { "Json File Analysis": { "Type": "Map", "ItemProcessor": { "ProcessorConfig": { "Mode": "DISTRIBUTED", "ExecutionType": "STANDARD" }, "StartAt": "Decode Json Node", "States": { "Decode Json Node": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "OutputPath": "$.Payload", "Parameters": { "Payload.$": "$", "FunctionName": "arn:aws:lambda:eu-east-1:1234567890:function:user-data-analysis-lambda:$LATEST" }, "Retry": [ { "ErrorEquals": [ "Lambda.ServiceException", "Lambda.AWSLambdaException", "Lambda.SdkClientException", "Lambda.TooManyRequestsException" ], "IntervalSeconds": 1, "MaxAttempts": 3, "BackoffRate": 2 } ], "End": true } } }, "ItemReader": { "Resource": "arn:aws:states:::s3:getObject", "ReaderConfig": { "InputType": "JSON", "JSONPath": "$.users" }, "Parameters": { "Bucket.$": "$.detail.bucket.name", "Key.$": "$.detail.object.key" } }, "MaxConcurrency": 1000, "Label": "JsonFileAnalysis", "End": true } } }
关键修改点说明
- 移除Map层级的
ItemsPath:原配置的$.users指向EventBridge事件数据中的字段,而非S3文件内容,无实际作用。 - 添加
ItemReader.ReaderConfig.JSONPath:该参数作用于从S3读取的JSON文件内容,指定要遍历的数组路径$.users,Step Functions会自动提取数组中的每个元素,传递给Lambda逐一处理。
此修改后,无论上传的是纯数组格式还是包含嵌套数组的JSON对象文件,Step Functions都能正常遍历并处理数组内的用户数据,同时支持4GB大文件的分片读取处理。
内容的提问来源于stack exchange,提问作者Ocean Sun
相关产品推荐
相关产品推荐

