简体   繁体   English

Jython - Scala 数组/列表不是 JSON 可在 python 脚本中序列化

[英]Jython - Scala array/list not JSON serializable within python script

I have a Scala class that wraps an avro record with getters and setters.我有一个 Scala class 用 getter 和 setter 包装 avro 记录。 Using Jython to allow users to write python scripts to process the Avro record and ultimately do a json.dumps on the new processed record.使用 Jython 允许用户编写 python 脚本来处理 Avro 记录,并最终在新处理的记录上执行json.dumps

The issue is, if the user wants to grab a value that is an Array from the record, the interpreter complains that the object is not JSON serializable.问题是,如果用户想从记录中获取一个数组值,解释器会抱怨 object 不是 JSON 可序列化的。

import json
json.dumps(<AClass>.getArray('myArray'))

The AClass is made available to any given python script at run time. AClass 在运行时可用于任何给定的 python 脚本。 Scala AClass: Scala A类:

class AClass {
  def getArray(fieldName: String): Array[Integer] = { 
    val value: GenericData.Array[T] = [....]
        value
      .asInstanceOf[GenericData.Array[T]]
      .asScala
      .toArray[T]
  }
}

I've tried a few other return types, 1) List[Integer] , 2) mutable.Buffer[Integer] , just the plain Avro generic Array 3) GenericData.Array[T] .我尝试了其他一些返回类型,1) List[Integer] ,2) mutable.Buffer[Integer] ,只是普通的 Avro 通用 Array 3) GenericData.Array[T] All give the same serialization error with the slightly varying objects:对于略有不同的对象,所有这些都给出了相同的序列化错误:

  1. Runtime exception occurred during Python processing. TypeError: List(1, 2, 3) is not JSON serializable.
  2. ... Buffer(1, 2, 3) is not JSON serializable
  3. ... [1, 2, 3] is not JSON serializable.

Now it seems that if we were to convert it to a list() from within the python script, it works fine.现在看来,如果我们要从 python 脚本中将其转换为list() ,它就可以正常工作。 This gave some leads but need it to happen at the Scala level.这提供了一些线索,但需要在 Scala 级别发生。

import json
json.dumps(list(<AClass>.getArray('myArray')))

Is there any way to achieve this?有什么办法可以做到这一点? What Scala / Java list type would translate directly into the python list type and/or be JSON serializable within the Jython py interpreter? What Scala / Java list type would translate directly into the python list type and/or be JSON serializable within the Jython py interpreter?

The json module in jython only accepts standard jython data types (that's why converting to list() works). jython 中的 json 模块仅接受标准 jython 数据类型(这就是转换为 list() 有效的原因)。 See: https://docs.python.org/3/library/json.html#py-to-json-table请参阅: https://docs.python.org/3/library/json.html#py-to-json-table

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM