2017-05-22 6 views
-1

JSONのnull値をpostgresqlに保存しようとしています。私は次のコードを使用する場合:null値を持つAPIからJSONを保存する

resume = Resume.create!({ 
    parsedres: {"Resume":{"xml:lang":"en","xmlns":"http://ns.hrxml.org/2006-02-28","xmlns:vos":"http://noresm.com/hr-xml/2006-02-28","ResumeId":{"IdValue":null}}} 
}) 

を私はエラーを取得:

NameError: undefined local variable or method `null' for main:Object

問題は、私がnullのために "" なしAPIデータを取得し、私はJSON.parseを使用

resume.parsedres = JSON.parse(response.body) 
resume.save 
です

それは

JSON::ParserError: 765: unexpected token at '<ParseResumeResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Code>Ack</Code><SubCode>Authentication/SubCode><Message>AccountID.</Message><CreditsRemaining>100</CreditsRemaining></ParseResumeResponse>' 

なぜスローJSON.parseは解釈しませんnull

+1

JSONパーサーエラーは、XML応答を解析しようとしているようです。レスポンスボディを調べて、実際にJSON(JSONコンテンツを取得するためにリクエストにヘッダーを含める必要があるかもしれません)かどうかを確認してみます。 –

+0

ありがとう、私は私のAPI呼び出しでJSONを要求しました。 resume.new レスポンス= RestClient :: Request.execute( メソッド:: post、 url: 'http:// APIの例'、 ペイロード:params、 **ヘッダー:{"Content-Type" = > "application/json"} ** ) – cruisertom

+0

ヘッダーに 'Accept' => 'application/json'を含めることもできます。それでも問題が解決しない場合、APIがJSONをサポートしておらず、XMLだけをサポートしている可能性があります。 –

答えて

1

最初に指定した例では、parsedresはJSONではなく、Ruby Hashリテラルです。リテラルはRubyのコードであるので、あなたはnullの代わりにRubyのnilキーワードを使用する必要があるだろう:

resume = Resume.create!({ 
    parsedres: {"Resume":{"xml:lang":"en","xmlns":"http://ns.hrxml.org/2006-02-28","xmlns:vos":"http://noresm.com/hr-xml/2006-02-28","ResumeId":{"IdValue":nil}}} 
}) 

あなたはAPIからJSON文字列を受け取った場合、あなたは上記のコードを使用してそれを解析することができるはずです:response.bodyは、XMLデータではなく、JSONであるように、例外がスローされるに基づいて

require 'json' 

resume = Resume.create!({ 
    parsedres: JSON.parse('{"Resume":{"xml:lang":"en","xmlns":"http://ns.hrxml.org/2006-02-28","xmlns:vos":"http://noresm.com/hr-xml/2006-02-28","ResumeId":{"IdValue":null}}}') 
}) 

、それが見えます。

+0

ありがとう! 'Accept' => 'application/json'のヘッダーがトリックでした! – cruisertom

関連する問題