英文:
Converting a string that represents a list into an actual list in Jython?
问题
我在Jython中有一个表示JSON数组列表的字符串:
[{"datetime": 1570216445000, "type": "test"},{"datetime": 1570216455000, "type": "test2"}]
如果我尝试迭代它,它只会迭代每个字符。如何使其迭代实际列表,以便我可以获取每个JSON数组?
背景信息 - 这个脚本在Apache NiFi中运行,下面是该字符串的来源代码:
from org.apache.commons.io import IOUtils
...
def process(self, inputStream):
text = IOUtils.toString(inputStream,StandardCharsets.UTF_8)
英文:
I have a string in Jython that represents a list of JSON arrays:
[{"datetime": 1570216445000, "type": "test"},{"datetime": 1570216455000, "type": "test2"}]
If I try to iterate over this though, it just iterates over each character. How can I make it iterate over the actual list so I can get each JSON array out?
Background info - This script is being run in Apache NiFi, below is the code that the string originates from:
from org.apache.commons.io import IOUtils
...
def process(self, inputStream):
text = IOUtils.toString(inputStream,StandardCharsets.UTF_8)
答案1
得分: 2
您可以解析一个类似于在Python中进行的JSON一样的JSON
。
示例代码:
import json
# 示例JSON文本
text = '[{"datetime": 1570216445000, "type": "test"},{"datetime": 1570216455000, "type": "test2"}]'
# 解析JSON文本
obj = json.loads(text)
# 'obj' 是一个字典
print(obj[0]['type'])
print(obj[1]['type'])
输出:
> jython json_string_to_object.py
test
test2
英文:
You can parse a JSON
similar to how you do it in Python
.
Sample Code:
import json
# Sample JSON text
text = '[{"datetime": 1570216445000, "type": "test"},{"datetime": 1570216455000, "type": "test2"}]'
# Parse the JSON text
obj = json.loads(text)
# 'obj' is a dictionary
print obj[0]['type']
print obj[1]['type']
Output:
> jython json_string_to_object.py
test
test2
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论