【问题标题】:extracting data from json in scala在scala中从json中提取数据
【发布时间】:2018-02-28 21:31:43
【问题描述】:
{
    "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 的新手。任何人都可以提出一个简单直接的方法来做到这一点。谢谢

【问题讨论】:

标签: java json scala url


【解决方案1】:

使用play-json 在此处查找https://mvnrepository.com/artifact/com.typesafe.play/play-json_2.12/2.6.8

您可以执行以下操作来提取searchResult

  1. 解析json

    val payload = Json.parse(str)

  2. 使用\\ 运算符获取所需的键值

    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...

【讨论】:

  • 非常感谢您的帮助。这真的很有帮助,而且很容易理解。 :)
【解决方案2】:

使用 circe-parser(另请参阅 https://circe.github.io/circe/parsing.html 如何使用它/添加到您的 build.sbt 的内容),以下 sn-p 将打印 Right(273088613147),这是来自 searchResultitemId

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 编写一个案例类,然后为它编写解码器/编码器,但我想,这不是您要问的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 2016-04-19
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 2019-03-26
    • 2014-07-08
    相关资源
    最近更新 更多