jquery
  • json
  • 2016-04-04 22 views 1 likes 
    1

    私はデータ属性の中にjsonを持っています。 http://jsonlint.com/のようなオンラインバリデーターで有効です。それでもエラーは起きます。なにが問題ですか?有効なjsonのjQuery解析jsonエラー

    HTML

    <div class="seo" data-seo-controller='{"values":{"child_count":"0","type":"tables"},"title":{"field":"\u00e5\u00e4\u00f6 llasdas","template":"This page has {{child_count}} {{type}}!","prefix":"","suffix":" - Products","fallback":"\u00e5\u00e4\u00f6 llasdas","full":"\u00e5\u00e4\u00f6 llasdas - Products","full-replaced":"\u00e5\u00e4\u00f6 llasdas - Products"},"description":{"field":"rwerwe wer &quot; &#039; ewrerte fsd :&#039;","fallback":"rwerwe wer &quot; &#039; ewrerte fsd :&#039;","full":"rwerwe wer &quot; &#039; ewrerte fsd :&#039;","full-replaced":"rwerwe wer &quot; &#039; ewrerte fsd :&#039;","template":"","prefix":"","suffix":"","limit":155},"url":{"edit":"http:\/\/localhost\/seo\/panel\/pages\/saved-value\/url","preview":"seo\/saved-value"}}'> 
    

    jQueryの

    $(document).ready(function() { 
        var json = $('.seo').attr('data-seo-controller'); 
        controller = jQuery.parseJSON(json); 
        console.log(controller); 
    }); 
    

    フィドル

    https://jsfiddle.net/q89hph0L/

    Uncaught SyntaxError: Unexpected token '

    UPDATE:

    コピーを文字列にJSONを貼り付け、それを解析あれば動作するようです。更新されたフィドル:https://jsfiddle.net/q89hph0L/4/

    したがって、データ属性としてjsonを持つことはできませんか?

    +1

    "が問題の原因です。それを処理しようとする。 –

    +0

    このデータの生成方法を知ることは面白いかもしれません – Brewal

    +0

    @Brewal with PHP。そのデータの中には、フォームやその他のデータをhtml属性に変換するものがあります。そのため、一部の文字がエスケープされます。 –

    答えて

    2

    &quot;ブラウザでレンダリングされます"、参照:How to escape double quotes in title attribute。それはあなたと同じユースケースです。

    ソリューションは\"jQuery.dataを使用しているときにも、JSON.parse()で文字列を解析する必要はありませんと&quot;を交換することです。 jsfiddle:https://jsfiddle.net/0qryjrya/が更新されました。

    関連する問題