arrays - 解析 JSON 对象,其值为 JSON 字符串数组
问题描述
我正在尝试解析具有以下格式的 JSON 字符串
{"edgeNodeRegistrationStatus": ["{\"CONFIRMED\":\"TRUE\"}"]}
我写了一个代码来解析它。
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText('{"edgeNodeRegistrationStatus": ["{\"CONFIRMED\":\"TRUE\"}"]}')
println(object["edgeNodeRegistrationStatus"][0])
我希望代码能够打印{"CONFIRMED":"TRUE"}
。但它抛出一个错误
Caught: groovy.json.JsonException: expecting a ',' or a ']', but got
the current character of 'C' with an int value of 67 on array index of 1
The current character read is 'C' with an int value of 67
expecting a ',' or a ']', but got
the current character of 'C' with an int value of 67 on array index of 1
line number 1
index number 35
{"edgeNodeRegistrationStatus": ["{"CONFIRMED":"TRUE"}"]}
...................................^
groovy.json.JsonException: expecting a ',' or a ']', but got
the current character of 'C' with an int value of 67 on array index of 1
The current character read is 'C' with an int value of 67
expecting a ',' or a ']', but got
the current character of 'C' with an int value of 67 on array index of 1
line number 1
index number 35
{"edgeNodeRegistrationStatus": ["{"CONFIRMED":"TRUE"}"]}
...................................^
at jdoodle.run(jdoodle.groovy:4)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Command exited with non-zero status 1
解决方案
在-String\"
内部使用''
只会"
在字符串本身内部(与""
-String 相同)。但是你想\"
为 JSON 引用(不是 groovy)。所以你需要\\"
改用。
除非您真的想使用该字符串进行测试,否则最好只在代码中生成您期望的 JSON。所以你不必为此而战。例如
JsonOutput.toJson([edgeNodeRegistrationStatus: [JsonOutput.toJson([CONFIRMED: "TRUE"])]])
推荐阅读
- javascript - 玩笑因 TypeError 失败: (0 , _user.default) 不是函数
- flutter - 在颤振中从 API 访问数据
- python - 在python中创建一个wilcoxon秩和测试的for循环以生成p值列表?
- ios - 在 SwiftUI 3 中交换选项卡视图指示器的配色方案
- python - 使用 Python 日志记录消息和标准错误
- json - 带 curl 的 Keycloak POST(创建用户和组)
- javascript - 使变量与对象方法相等
- windows - 如何检测正在进行的 webex 会议或 google 会议
- bash - 如何使用自定义文件夹中的所有脚本,例如 macOS 中的本机 shell 命令
- javascript - 在本地捕获 mux.monitor 对象