Perché Ruby non può analizzare il file JSON locale?

Sep 05 2020

Ho una domanda correlata qui , ma sto pubblicando un'altra domanda per concentrarmi su una parte specifica del problema.

Obiettivo: aggiungere uno script alla mia app Ruby che può leggere un file JSON locale, analizzarlo in un hash Ruby e accedere alle proprietà al suo interno.

Sistema: CentOS 7

File: /tmp/valid.jsonfile salvato localmente :

{
  "firstName": "John",
  "lastName": "Smith",
  "isAlive": true,
  "age": 27,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "office",
      "number": "646 555-4567"
    }
  ],
  "children": [],
  "spouse": null
}

(Quell'oggetto è stato preso in prestito dall'articolo di Wikipedia su JSON nel tentativo di assicurarmi che il mio problema non sia JSON non valido.)

Codice:

require 'json'
data = File.read("/tmp/valid.json")
$evm.log(:info, data) #writes to log file, where I can see content of my JSON file $evm.log(:info, "is data a hash ? ")
$evm.log(:info, data.is_a?(Hash).to_s) # prints false $evm.log(:info, "is data a string? ")
$evm.log(:info, data.is_a?(String).to_s) # prints true $evm.log(:info, "can I parse data?")
valid_ob = JSON.parse(data)
$evm.log(:info, "just parsed it, now print it") $evm.log(:info, valid_ob)

L'ultima riga viene stampata:

NoMethodError: undefined method `gsub' for #<Hash:0x0000000020951f
a8>

Perché Ruby non può analizzare questa stringa?

Risposte

1 anothermh Sep 05 2020 at 05:26

Il problema è qualcosa in qualunque cosa tu abbia assegnato $evm. Il messaggio di errore:

NoMethodError: undefined method `gsub' for #<Hash:>

indica che quando chiami

$evm.log(:info, valid_ob)

il logmetodo sta tentando di chiamare gsubsu valid_ob. Molto probabilmente, logè destinato ad accettare solo stringhe e non esegue il controllo del tipo sull'oggetto che riceve.

Se hai bisogno di un modo semplice e interattivo per eseguire questo codice Ruby senza utilizzare questo $evmoggetto, esegui irbnella tua console e inizia a digitare il tuo codice Ruby per analizzare i dati JSON:

require 'json'
 => true
data = File.read('/tmp/valid.json')
data.class
 => String
hash = JSON.parse(data)
hash.class
 => Hash
hash
 => {"firstName"=>"John", "lastName"=>"Smith", "isAlive"=>true, "age"=>27, "address"=>{"streetAddress"=>"21 2nd Street", "city"=>"New York", "state"=>"NY", "postalCode"=>"10021-3100"}, "phoneNumbers"=>[{"type"=>"home", "number"=>"212 555-1234"}, {"type"=>"office", "number"=>"646 555-4567"}], "children"=>[], "spouse"=>nil}
2 JustAnotherDisplayName Sep 05 2020 at 05:28

Hai provato a stampare l'oggetto normalmente, invece di usare "$ evm.log"? JSON.parse restituisce un hash e sembra che il tuo logger stia tentando di eseguire un metodo gsub inesistente su di esso.