使用JavaScriptSerializer解析JSON时无法正确提取数值类型字段的问题求助
使用JavaScriptSerializer解析JSON时无法正确提取数值类型字段的问题求助
嘿,我仔细看了你的问题、代码和对应的JSON结构,发现两个核心问题导致你拿不到那些数值字段的值,咱们一步步来解决:
问题1:字段路径找错了!
你要提取的labelWidthInUnits、labelHeightInUnits这些数值字段,根本不在JSON的根节点,而是嵌套在test数组的第一个对象里。你的代码现在直接在response_data(根对象)里找这些键,肯定找不到,自然就会触发默认的"-"逻辑。
问题2:labelWidthInUnits的处理代码有语法漏洞
看你这段代码:
# Extract the label_width_in_units value if "labelWidthInUnits" in response_data: width_value = response_data["labelWidthInUnits"] label_width_in_units = response_data["labelWidthInUnits"] #else: label_width_in_units = "-"
你把else注释掉后,不管前面有没有找到目标字段,最后都会把label_width_in_units覆盖成"-"——哪怕前面成功拿到了值,也会被这行代码清空,这也是你一直拿到"-"的关键原因之一。
修改后的完整代码
我把这两个问题都修复了,还优化了一些逻辑,你可以直接试用:
import clr clr.AddReference('System.Web.Extensions') # Add reference to the System.Web.Extensions assembly from System.Web.Script.Serialization import JavaScriptSerializer # Import JavaScriptSerializer # Assuming _loopAPIstatus and _looplabeldata are available in the context status_code = _loopAPIstatus.Value api_response = _looplabeldata.Value def get_label_state(api_response, status_code): # Directly convert status_code to an integer try: status_code = int(status_code) # Ensure the status code is an integer except ValueError: return "InvalidStatusCode", "", "", "" # Handle invalid status codes # Initialize variables with default values final_label_state = "" label_width_in_units = "-" label_height_in_units = "-" revision = "-" # Check the HTTP status code if status_code == 200: try: # Initialize the JavaScriptSerializer to parse JSON serializer = JavaScriptSerializer() response_data = serializer.DeserializeObject(api_response) # Extract root-level string fields (original logic works here) if "workflowStep" in response_data: final_label_state = response_data["workflowStep"] else: final_label_state = "workflowStepNotFound" if "revision" in response_data: revision = response_data["revision"] # Extract nested numeric fields from the test array if "test" in response_data and len(response_data["test"]) > 0: test_item = response_data["test"][0] # Get the first item in the test array if "labelWidthInUnits" in test_item: # Convert .NET numeric type to string (remove str() if you need numeric value) label_width_in_units = str(test_item["labelWidthInUnits"]) if "labelHeightInUnits" in test_item: label_height_in_units = str(test_item["labelHeightInUnits"]) except Exception as e: final_label_state = f"Error: {str(e)}" # Add error message for easier debugging elif status_code == 404: final_label_state = "NotFound" else: final_label_state = "UnknownStatus" # Return the results return final_label_state, label_width_in_units, label_height_in_units, revision # Now update the variables with the final result label_state, label_width_in_units, label_height_in_units, revision = get_label_state(api_response, status_code) _labelstate.Value = label_state _labelwidth.Value = label_width_in_units _labelheight.Value = label_height_in_units _revision.Value = revision
额外说明
- 我把所有默认值
"-"提前初始化了,避免重复编写else逻辑,代码更简洁。 - 提取
test数组时,先检查数组是否存在且不为空,防止出现索引越界的错误。 - 如果你的目标变量支持直接存储数值类型,去掉代码里的
str()即可,IronPython可以直接处理.NET解析出来的数值类型。
备注:内容来源于stack exchange,提问作者sniper2100
相关产品推荐
相关产品推荐

