gpt4 book ai didi

Scala JSON 差异

转载 作者:行者123 更新时间:2023-12-02 00:05:58 30 4
gpt4 key购买 nike

我有两个具有完全相同键的 JSON。

val json1 = 
"""{
'name': 'Henry',
'age' : 26,
'activities' : {
'school': 'basketball club',
'after-school': 'chess'
}
}"""

val json2 =
"""{
'name': 'David',
'age' : 23,
'activities' : {
'school': 'baseball club',
'after-school': 'programming'
}
}"""

我想知道这两个json的区别,比如:

name = Henry, David
age = 23, 26
activities.school= basketball club, baseball club
activities.after-school=chess, programming

它不必遵循上述格式,但我想获取不同的键和值。

最佳答案

您可以尝试 diffson,一个基于 circe 的库:https://github.com/gnieh/diffson

例子:

import diffson._
import diffson.lcs._
import diffson.circe._
import diffson.jsonpatch._
import diffson.jsonpatch.lcsdiff._

import io.circe._
import io.circe.parser._

import cats._
import cats.implicits._

implicit val lcs = new Patience[Json]

val json1 = parse("""{
| "a": 1,
| "b": true,
| "c": ["test", "plop"]
|}""".stripMargin)

val json2 = parse("""{
| "a": 6,
| "c": ["test2", "plop"],
| "d": false
|}""".stripMargin)

val patch =
for {
json1 <- json1
json2 <- json2
} yield diff(json1, json2)

会返回:

[{
"op":"replace",
"path":"/a",
"value":6
},{
"op":"remove",
"path":"/b"
},{
"op":"replace",
"path":"/c/0",
"value":"test2"
},{
"op":"add",
"path":"/d",
"value":false
}]

基本上,您可以根据您的确切目的连接“添加”部分值。

关于Scala JSON 差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60621632/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com