使用 Circe 将字段添加到 json [英] Adding field to a json using Circe
问题描述
我正在阅读 circe 文档,但不知道如何处理以下问题.
I am going trough the circe documentation and can't figure out how to handle the following.
我只想在主 JSON 对象中添加一个带有对象的字段.
I would simply like to add a field with an object in said the main JSON object.
{
Fieldalreadythere: {}
"Newfield" : {}
}
我只想在对象中添加Newfield
.为了提供一些上下文,我正在处理 Json-ld.我只想添加一个上下文对象.@语境: {}请参见下面的示例:
I just want to add the Newfield
in the object. To give a bit of context I am dealing with Json-ld. I just want to add a context object. @context: {}
See example below:
{
"@context": {
"@version": 1.1,
"xsd": "http://www.w3.org/2001/XMLSchema#",
"foaf": "http://xmlns.com/foaf/0.1/",
"foaf:homepage": { "@type": "@id" },
"picture": { "@id": "foaf:depiction", "@type": "@id" }
},
"@id": "http://me.markus-lanthaler.com/",
"@type": "foaf:Person",
"foaf:name": "Markus Lanthaler",
"foaf:homepage": "http://www.markus-lanthaler.com/",
"picture": "http://twitter.com/account/profile_image/markuslanthaler"
}
我想添加上下文对象,仅此而已.
I would like to add the context object, that's all.
我怎么能用circe做到这一点.官方文档中的例子主要是讲修改值,但没有实际添加字段等.
How can I do that with circe. The example in the official documentation mostly talk about modifying the value, but nothing to actually add field and so on.
推荐答案
看一看 JsonObject.有 :+ 方法可以满足您的需求.
Take a look at JsonObject. There is :+ method that does what you want.
这是一个简单的例子:
import io.circe.generic.auto._
import io.circe.parser
import io.circe.syntax._
object CirceAddFieldExample extends App {
val jsonStr = """{
Fieldalreadythere: {}
}"""
val json = parser.parse(jsonStr)
val jsonObj = json match {
case Right(value) => value.asObject
case Left(error) => throw error
}
val jsonWithContextField = jsonObj.map(_.+:("@context", contextObj.asJson))
}
这篇关于使用 Circe 将字段添加到 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!