从scala中的json中提取数据
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从scala中的json中提取数据相关的知识,希望对你有一定的参考价值。
{
"findItemsByKeywordsResponse": [{
"ack": ["Success"],
"version": ["1.13.0"],
"timestamp": ["2018-02-28T09:52:48.736Z"],
"searchResult": [{
"@count": "1",
"item": [{
"itemId": ["273088613147"],
"title": ["MTG Air Elemental *ALPHA*"],
"globalId": ["EBAY-ENCA"],
"primaryCategory": [{
"categoryId": ["38292"],
"categoryName": ["MTG Individual Cards"]
}],
"galleryURL": ["http://thumbs4.ebaystatic.com/m/mrUjH7CtVxARfthfKH3wYAw/140.jpg"],
"viewItemURL": ["http://www.ebay.com/itm/MTG-Air-Elemental-ALPHA-/273088613147"],
"paymentMethod": ["PayPal"],
"autoPay": ["false"],
"postalCode": ["M4S2H7"],
"location": ["Canada"],
"country": ["CA"],
"shippingInfo": [{
"shippingServiceCost": [{
"@currencyId": "USD",
"__value__": "0.0"
}],
"shippingType": ["Free"],
"shipToLocations": ["Worldwide"],
"expeditedShipping": ["false"],
"oneDayShippingAvailable": ["false"],
"handlingTime": ["1"]
}],
"sellingStatus": [{
"currentPrice": [{
"@currencyId": "CAD",
"__value__": "25.0"
}],
"convertedCurrentPrice": [{
"@currencyId": "USD",
"__value__": "19.6"
}],
"sellingState": ["Active"],
"timeLeft": ["P29DT19H50M26S"]
}],
"listingInfo": [{
"bestOfferEnabled": ["false"],
"buyItNowAvailable": ["false"],
"startTime": ["2018-02-28T05:43:14.000Z"],
"endTime": ["2018-03-30T05:43:14.000Z"],
"listingType": ["FixedPrice"],
"gift": ["false"]
}],
"returnsAccepted": ["false"],
"condition": [{
"conditionId": ["3000"],
"conditionDisplayName": ["Used"]
}],
"isMultiVariationListing": ["false"],
"topRatedListing": ["false"]
}]
}],
"paginationOutput": [{
"pageNumber": ["1"],
"entriesPerPage": ["100"],
"totalPages": ["1"],
"totalEntries": ["1"]
}],
"itemSearchURL": ["http://www.ebay.com/sch/i.html?_nkw=mtg+air+elemental+alpha&_ddo=1&_ipg=100&_pgn=1"]
}]
}
我想在第一行中提取“SearchResult”的值。我查看了stackoverflow的提示,但我感到困惑,我是Scala的新手。任何人都可以建议一个简单而直接的方法。谢谢
答案
使用play-json
在这里找到https://mvnrepository.com/artifact/com.typesafe.play/play-json_2.12/2.6.8
您可以执行以下操作来提取searchResult
- 解析json
val payload = Json.parse(str)
- 使用
\
运算符获取所需的键值val payload = Json.parse(str) payload \ "searchResult"
Scala REPL
scala> :paste
// Entering paste mode (ctrl-D to finish)
val str = """{"findItemsByKeywordsResponse":[{"ack":["Success"],"version":["1.13.0"],"timestamp":["2018-02-28T09:52:48.736Z"],"searchResult":[{"@count":"1","item":[{"itemId":["273088613147"],"title":["MTG Air Elemental *ALPHA*"],"globalId":["EBAY-ENCA"],"primaryCategory":[{"categoryId":["38292"],"categoryName":["MTG Individual Cards"]}],"galleryURL":["http://thumbs4.ebaystatic.com/m/mrUjH7CtVxARfthfKH3wYAw/140.jpg"],"viewItemURL":["http://www.ebay.com/itm/MTG-Air-Elemental-ALPHA-/273088613147"],"paymentMethod":["PayPal"],"autoPay":["false"],"postalCode":["M4S2H7"],"location":["Canada"],"country":["CA"],"shippingInfo":[{"shippingServiceCost":[{"@currencyId":"USD","__value__":"0.0"}],"shippingType":["Free"],"shipToLocations":["Worldwide"],"expeditedShipping":["false"],"oneDayShippingAvailable":["false"],"handlingTime":["1"]}],"sellingStatus":[{"currentPrice":[{"@currencyId":"CAD","__value__":"25.0"}],"convertedCurrentPrice":[{"@currencyId":"USD","__value__":"19.6"}],"sellingState":["Active"],"timeLeft":["P29DT19H50M26S"]}],"listingInfo":[{"bestOfferEnabled":["false"],"buyItNowAvailable":["false"],"startTime":["2018-02-28T05:43:14.000Z"],"endTime":["2018-03-30T05:43:14.000Z"],"listingType":["FixedPrice"],"gift":["false"]}],"returnsAccepted":["false"],"condition":[{"conditionId":["3000"],"conditionDisplayName":["Used"]}],"isMultiVariationListing":["false"],"topRatedListing":["false"]}]}],"paginationOutput":[{"pageNumber":["1"],"entriesPerPage":["100"],"totalPages":["1"],"totalEntries":["1"]}],"itemSearchURL":["http://www.ebay.com/sch/i.html?_nkw=mtg+air+elemental+alpha&_ddo=1&_ipg=100&_pgn=1"]}]}"""
// Exiting paste mode, now interpreting.
str: String = {"findItemsByKeywordsResponse":[{"ack":["Success"],"version":["1.13.0"],"timestamp":["2018-02-28T09:52:48.736Z"],"searchResult":[{"@count":"1","item":[{"itemId":["273088613147"],"title":["MTG Air Elemental *ALPHA*"],"globalId":["EBAY-ENCA"],"primaryCategory":[{"categoryId":["38292"],"categoryName":["MTG Individual Cards"]}],"galleryURL":["http://thumbs4.ebaystatic.com/m/mrUjH7CtVxARfthfKH3wYAw/140.jpg"],"viewItemURL":["http://www.ebay.com/itm/MTG-Air-Elemental-ALPHA-/273088613147"],"paymentMethod":["PayPal"],"autoPay":["false"],"postalCode":["M4S2H7"],"location":["Canada"],"country":["CA"],"shippingInfo":[{"shippingServiceCost":[{"@currencyId":"USD","__value__":"0.0"}],"shippingType":["Free"],"shipToLocations":["Worldwide"],"expeditedShi...
scala> val payload = Json.parse(str)
payload: play.api.libs.json.JsValue = {"findItemsByKeywordsResponse":[{"ack":["Success"],"version":["1.13.0"],"timestamp":["2018-02-28T09:52:48.736Z"],"searchResult":[{"@count":"1","item":[{"itemId":["273088613147"],"title":["MTG Air Elemental *ALPHA*"],"globalId":["EBAY-ENCA"],"primaryCategory":[{"categoryId":["38292"],"categoryName":["MTG Individual Cards"]}],"galleryURL":["http://thumbs4.ebaystatic.com/m/mrUjH7CtVxARfthfKH3wYAw/140.jpg"],"viewItemURL":["http://www.ebay.com/itm/MTG-Air-Elemental-ALPHA-/273088613147"],"paymentMethod":["PayPal"],"autoPay":["false"],"postalCode":["M4S2H7"],"location":["Canada"],"country":["CA"],"shippingInfo":[{"shippingServiceCost":[{"@currencyId":"USD","__value__":"0.0"}],"shippingType":["Free"],"shipToLocations":["Worldwide"]...
scala> payload \ "searchResult"
res7: Seq[play.api.libs.json.JsValue] = List([{"@count":"1","item":[{"itemId":["273088613147"],"title":["MTG Air Elemental *ALPHA*"],"globalId":["EBAY-ENCA"],"primaryCategory":[{"categoryId":["38292"],"categoryName":["MTG Individual Cards"]}],"galleryURL":["http://thumbs4.ebaystatic.com/m/mrUjH7CtVxARfthfKH3wYAw/140.jpg"],"viewItemURL":["http://www.ebay.com/itm/MTG-Air-Elemental-ALPHA-/273088613147"],"paymentMethod":["PayPal"],"autoPay":["false"],"postalCode":["M4S2H7"],"location":["Canada"],"country":["CA"],"shippingInfo":[{"shippingServiceCost":[{"@currencyId":"USD","__value__":"0.0"}],"shippingType":["Free"],"shipToLocations":["Worldwide"],"expeditedShipping":["false"],"oneDayShippingAvailable":["false"],"handlingTime":["1"]}],"sellingStatus":[{"currentPrice...
scala> val searchResult = payload \ "searchResult"
searchResult: Seq[play.api.libs.json.JsValue] = List([{"@count":"1","item":[{"itemId":["273088613147"],"title":["MTG Air Elemental *ALPHA*"],"globalId":["EBAY-ENCA"],"primaryCategory":[{"categoryId":["38292"],"categoryName":["MTG Individual Cards"]}],"galleryURL":["http://thumbs4.ebaystatic.com/m/mrUjH7CtVxARfthfKH3wYAw/140.jpg"],"viewItemURL":["http://www.ebay.com/itm/MTG-Air-Elemental-ALPHA-/273088613147"],"paymentMethod":["PayPal"],"autoPay":["false"],"postalCode":["M4S2H7"],"location":["Canada"],"country":["CA"],"shippingInfo":[{"shippingServiceCost":[{"@currencyId":"USD","__value__":"0.0"}],"shippingType":["Free"],"shipToLocations":["Worldwide"],"expeditedShipping":["false"],"oneDayShippingAvailable":["false"],"handlingTime":["1"]}],"sellingStatus":[{"curr...
scala> searchResult
res8: Seq[play.api.libs.json.JsValue] = List([{"@count":"1","item":[{"itemId":["273088613147"],"title":["MTG Air Elemental *ALPHA*"],"globalId":["EBAY-ENCA"],"primaryCategory":[{"categoryId":["38292"],"categoryName":["MTG Individual Cards"]}],"galleryURL":["http://thumbs4.ebaystatic.com/m/mrUjH7CtVxARfthfKH3wYAw/140.jpg"],"viewItemURL":["http://www.ebay.com/itm/MTG-Air-Elemental-ALPHA-/273088613147"],"paymentMethod":["PayPal"],"autoPay":["false"],"postalCode":["M4S2H7"],"location":["Canada"],"country":["CA"],"shippingInfo":[{"shippingServiceCost":[{"@currencyId":"USD","__value__":"0.0"}],"shippingType":["Free"],"shipToLocations":["Worldwide"],"expeditedShipping":["false"],"oneDayShippingAvailable":["false"],"handlingTime":["1"]}],"sellingStatus":[{"currentPrice...
另一答案
使用circe-parser(另见https://circe.github.io/circe/parsing.html如何使用它/将什么添加到你的build.sbt
),下面的代码片段将打印Right(273088613147)
,这是itemId
中的searchResult
:
import io.circe._, io.circe.parser._
def myParse(jsonString: String) {
val result = parse(jsonString) match {
case Left(failure) => println("Invalid JSON :(")
case Right(json) => {
val cursor = json.hcursor
println(cursor.downField("findItemsByKeywordsResponse").downArray.
downField("searchResult").downArray.
downField("item").downArray.
downField("itemId").downArray.as[String])
}
}
}
或者,您可以为您的JSON编写一个case类,然后为它编写解码器/编码器,但我想,这不是您要求的。
以上是关于从scala中的json中提取数据的主要内容,如果未能解决你的问题,请参考以下文章
在 Play2 / Scala 中从内存中的 MultipartFormData 中提取文件