从Ruby中的JSON文件解析并从嵌套哈希中提取数字

问题描述 投票:16回答:3

现在我正在从Ruby中的JSON文件中提取信息。那么如何从以下文本文件中提取“得分”一词旁边的数字呢?例如,我想要打开0.6748984055823062,0.6280145725181376。

{
  "sentiment_analysis": [
    {
      "positive": [
        {
          "sentiment": "Popular",
          "topic": "games",
          "score": 0.6748984055823062,
          "original_text": "Popular games",
          "original_length": 13,
          "normalized_text": "Popular games",
          "normalized_length": 13,
          "offset": 0
        },
        {
          "sentiment": "engaging",
          "topic": "pop culture-inspired games",
          "score": 0.6280145725181376,
          "original_text": "engaging pop culture-inspired games",
          "original_length": 35,
          "normalized_text": "engaging pop culture-inspired games",
          "normalized_length": 35,
          "offset": 370
        },
     "negative": [
    {
      "sentiment": "get sucked into",
      "topic": "the idea of planning",
      "score": -0.7923352042939829,
      "original_text": "Students get sucked into the idea of planning",
      "original_length": 45,
      "normalized_text": "Students get sucked into the idea of planning",
      "normalized_length": 45,
      "offset": 342
    },
    {
      "sentiment": "be daunted",
      "topic": null,
      "score": -0.5734506634410159,
      "original_text": "initially be daunted",
      "original_length": 20,
      "normalized_text": "initially be daunted",
      "normalized_length": 20,
      "offset": 2104
    },

我试过的是我可以使用JSON方法读取文件并将文本文件设置为哈希变量。

require 'json'
json = JSON.parse(json_string)
json ruby parsing
3个回答
6
投票

您可以使用Array#map收集评论。

reviews = json['sentiment_analysis'][0]
positive_reviews = reviews['positive']
negative_reviews = reviews['negative']

positive_reviews.map { |review| review['score'] }
=> [0.6748984055823062, 0.6280145725181376]

negative_reviews.map { |review| review['score'] }
=> [-0.7923352042939829, -0.5734506634410159]

希望这可以帮助!


30
投票

使用JSON类:

导入文件:

require "json"
file = File.open "/path/to/your/file.json"
data = JSON.load file

您可以选择立即关闭它:

file.close

该文件如下所示:

{
  "title": "Facebook",
  "url": "https://www.facebook.com",
  "posts": [
    "lemon-car",
    "dead-memes"
  ]
}

该文件现在可以像这样读取:

data["title"]
=> "Facebook"
data.keys
=> ["title", "url", "posts"]
data['posts']
=> ["lemon-car", "dead-memes"]
data["url"]
=> "https://www.facebook.com"

希望这有帮助!


9
投票

Parse Data from File

data_hash = JSON.parse(File.read('file-name-to-be-read.json'))

然后只是映射数据!

reviews = data_hash['sentiment_analysis'].first
reviews.map do |sentiment, reviews|
  puts "#{sentiment} #{reviews.map { |review| review['score'] }}"
end

我认为这是最简单的答案。

© www.soinside.com 2019 - 2024. All rights reserved.