I am creating a tool using arcpy to get a web map as json and print it through a layout template. I could get the aprx through the code snippet below, but the tool's outcome legend differs from ArcGIS Pro as shown in the images. The problem happens when there is a group layer as well as labels for sub-items. So the legend doesn't include second group layer names and instead makes duplicate labels for sub-items.
result = arcpy.mp.ConvertWebMapToArcGISProject(webmap_json, layout_template, "Layers Map Frame")
aprx = result.ArcGISProject
layout = aprx.listLayouts()[0]
layout.exportToPDF(out_pdf=output)
Output from the tool with duplicate labels | The actual layer in ArcGIS Pro |