Home > Blockchain >  handling a well-formed JSON file of an array of objects
handling a well-formed JSON file of an array of objects

Time:11-15

A JSON string string passes the jsonlint test.

response = [
  {
    "article" : {
      "info" : {
        "initial" : {
          "articleIds" : [
            "7461221587662919569"
          ],
        }
      },
      "text" : "where they would 'transfer to' next.",
      "lang" : "en",
    }
  },
  {
    "article" : {
      "info" : {
        "initial" : {
          "articleIds" : [
            "6613144915874808065"
          ],
        }
      },
      "text" : "produto regional.",
      "lang" : "pt"
    }
  }
]

However, after processing

require 'json'
file = File.read('/Users/main/jugg//article_samples.js')
data_hash = JSON.parse(file)

One is left with an array, whereas more frequently a hash with a name labels a subsequent array, where one works with that nomenclature such as response['data']

But in this case the array is not accessible via response[0]. How can this be considered as an array in order to process each individual element collection.each do |member|?

A curiosity: data_hash.class => NilClass

CodePudding user response:

The response = ... code from article_samples.js is JavaScript, not JSON. This initializes a variable named response with a JavaScript array.

To use this as JSON, then rename the file to article_samples.json and remove response = from the file. The first line should start with [.

Now your second block of code should work just fine as long as the article_samples.json file is in the correct path.

On a side note, I suggest that you find a way to make the path more flexible. The way you have it currently hard coded is tied directly to your current machine's file system. This won't work if you want to run this code from another machine because the folder /Users/main/jugg probalby won't exist.

If this is a web server with ruby on rails, then one solution is to create an environment variable with the path where this file is stored.

  • Related