在Jython中将表示列表的字符串转换为实际列表?

huangapple go评论53阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年1月7日 02:35:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/59617227.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定