如何加密 JSON 字段,然后将该字段读回 JSON

How to encrypt a JSON field and then read that field back into the JSON

我能够从包含 JSON 对象的列中检索要加密的字段,加密该字段后,我想将其读回 JSON。这就是我的数据框的样子:

json: struct
 id:string
 pii:string
 type:string
 dataContentType:string
 dataSchema:string
 time:string
enqueuedTime:date

两列(JSON,EnqueuedTime)所以我希望能够获取 pii 值并对其进行加密,然后将其读回 JSON 列。我们当前的解决方案是将 JSON 展平为单独的列,但客户希望保留原始的 JSON 结构。我正在努力寻找一种方法将加密值读回 JSON 或通过 PySpark 反转 JSON 的扁平化。

这个最小的独立示例向您展示了如何使用 withColumnwithField 和自定义 udf 函数加密 pii 字段:

import pyspark.sql.functions as F
import pyspark.sql.types as T

structureSchema = T.StructType([
          T.StructField('json', T.StructType([
             T.StructField('id', T.StringType(), True),
             T.StructField('pii', T.StringType(), True),
             ])),
         ])

df = spark.createDataFrame([(("123", "some json"),), (("456", "some more json"),)], structureSchema)
df.show()

@udf(returnType=T.StringType()) 
def encrypt_json(s):
  return "Enc: " + s

df_result = df.withColumn("json", F.col("json").withField("pii", encrypt_json(F.col("json.pii"))))
df_result.show()

输出:

+--------------------+
|                json|
+--------------------+
|    {123, some json}|
|{456, some more j...|
+--------------------+

+--------------------+
|                json|
+--------------------+
|{123, Enc: some j...|
|{456, Enc: some m...|
+--------------------+

你当然需要用你自己的加密函数替换encrypt_jsonudf函数。