Creating object from JSON and parsing JSON - different results












-1














I am trying to use JQuery to parse some JSON being sent back from an AJAX call. It appears to be failing to parse, and JSLint also says it's invalid JSON.



However, if I create the object directly, it works and I am able to loop through it - please see below:



var json = {layers:[{layer1:[17,16,15,14,12]}]}
alert(json)// <- This works and output object Object

var somestring = "{layers:[{layer1:[17,16,15,14,12]}]}"
var parsing = JSON.parse(somestring)
alert(parsing) // <- this doesn't and breaks on parse

// The below code will work provided the parsing is commented out

json.layers.forEach(function (outerObj)
{
Object.keys(outerObj).forEach(function (key)
{
outerObj[key].forEach(function (item)
{
alert(item)
});
});
});


I'm struggling to wrap my head around why it won't parse, but appears to work.



Edit



I realise by wrapping quotes around layers and layer1 fixes it, just not sure why it works one way - but not the other.










share|improve this question




















  • 1




    If you're using the AJAX functions in jQuery (with data type set to JSON) you won't have to parse it - jQuery does that for you. Trying to parse an already-parsed JSON string will give you an error iirc.
    – Andy
    Nov 11 at 18:05












  • Great tip, thanks very much. Totally forgot about dataType am using this now.
    – Aphire
    Nov 11 at 18:11






  • 3




    JSON keys officially should be with surrounded with apices. When you have a JSON object string, it expects you use JSON syntax correctly
    – quirimmo
    Nov 11 at 18:18
















-1














I am trying to use JQuery to parse some JSON being sent back from an AJAX call. It appears to be failing to parse, and JSLint also says it's invalid JSON.



However, if I create the object directly, it works and I am able to loop through it - please see below:



var json = {layers:[{layer1:[17,16,15,14,12]}]}
alert(json)// <- This works and output object Object

var somestring = "{layers:[{layer1:[17,16,15,14,12]}]}"
var parsing = JSON.parse(somestring)
alert(parsing) // <- this doesn't and breaks on parse

// The below code will work provided the parsing is commented out

json.layers.forEach(function (outerObj)
{
Object.keys(outerObj).forEach(function (key)
{
outerObj[key].forEach(function (item)
{
alert(item)
});
});
});


I'm struggling to wrap my head around why it won't parse, but appears to work.



Edit



I realise by wrapping quotes around layers and layer1 fixes it, just not sure why it works one way - but not the other.










share|improve this question




















  • 1




    If you're using the AJAX functions in jQuery (with data type set to JSON) you won't have to parse it - jQuery does that for you. Trying to parse an already-parsed JSON string will give you an error iirc.
    – Andy
    Nov 11 at 18:05












  • Great tip, thanks very much. Totally forgot about dataType am using this now.
    – Aphire
    Nov 11 at 18:11






  • 3




    JSON keys officially should be with surrounded with apices. When you have a JSON object string, it expects you use JSON syntax correctly
    – quirimmo
    Nov 11 at 18:18














-1












-1








-1







I am trying to use JQuery to parse some JSON being sent back from an AJAX call. It appears to be failing to parse, and JSLint also says it's invalid JSON.



However, if I create the object directly, it works and I am able to loop through it - please see below:



var json = {layers:[{layer1:[17,16,15,14,12]}]}
alert(json)// <- This works and output object Object

var somestring = "{layers:[{layer1:[17,16,15,14,12]}]}"
var parsing = JSON.parse(somestring)
alert(parsing) // <- this doesn't and breaks on parse

// The below code will work provided the parsing is commented out

json.layers.forEach(function (outerObj)
{
Object.keys(outerObj).forEach(function (key)
{
outerObj[key].forEach(function (item)
{
alert(item)
});
});
});


I'm struggling to wrap my head around why it won't parse, but appears to work.



Edit



I realise by wrapping quotes around layers and layer1 fixes it, just not sure why it works one way - but not the other.










share|improve this question















I am trying to use JQuery to parse some JSON being sent back from an AJAX call. It appears to be failing to parse, and JSLint also says it's invalid JSON.



However, if I create the object directly, it works and I am able to loop through it - please see below:



var json = {layers:[{layer1:[17,16,15,14,12]}]}
alert(json)// <- This works and output object Object

var somestring = "{layers:[{layer1:[17,16,15,14,12]}]}"
var parsing = JSON.parse(somestring)
alert(parsing) // <- this doesn't and breaks on parse

// The below code will work provided the parsing is commented out

json.layers.forEach(function (outerObj)
{
Object.keys(outerObj).forEach(function (key)
{
outerObj[key].forEach(function (item)
{
alert(item)
});
});
});


I'm struggling to wrap my head around why it won't parse, but appears to work.



Edit



I realise by wrapping quotes around layers and layer1 fixes it, just not sure why it works one way - but not the other.







javascript jquery json






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 18:08

























asked Nov 11 at 18:02









Aphire

7701039




7701039








  • 1




    If you're using the AJAX functions in jQuery (with data type set to JSON) you won't have to parse it - jQuery does that for you. Trying to parse an already-parsed JSON string will give you an error iirc.
    – Andy
    Nov 11 at 18:05












  • Great tip, thanks very much. Totally forgot about dataType am using this now.
    – Aphire
    Nov 11 at 18:11






  • 3




    JSON keys officially should be with surrounded with apices. When you have a JSON object string, it expects you use JSON syntax correctly
    – quirimmo
    Nov 11 at 18:18














  • 1




    If you're using the AJAX functions in jQuery (with data type set to JSON) you won't have to parse it - jQuery does that for you. Trying to parse an already-parsed JSON string will give you an error iirc.
    – Andy
    Nov 11 at 18:05












  • Great tip, thanks very much. Totally forgot about dataType am using this now.
    – Aphire
    Nov 11 at 18:11






  • 3




    JSON keys officially should be with surrounded with apices. When you have a JSON object string, it expects you use JSON syntax correctly
    – quirimmo
    Nov 11 at 18:18








1




1




If you're using the AJAX functions in jQuery (with data type set to JSON) you won't have to parse it - jQuery does that for you. Trying to parse an already-parsed JSON string will give you an error iirc.
– Andy
Nov 11 at 18:05






If you're using the AJAX functions in jQuery (with data type set to JSON) you won't have to parse it - jQuery does that for you. Trying to parse an already-parsed JSON string will give you an error iirc.
– Andy
Nov 11 at 18:05














Great tip, thanks very much. Totally forgot about dataType am using this now.
– Aphire
Nov 11 at 18:11




Great tip, thanks very much. Totally forgot about dataType am using this now.
– Aphire
Nov 11 at 18:11




3




3




JSON keys officially should be with surrounded with apices. When you have a JSON object string, it expects you use JSON syntax correctly
– quirimmo
Nov 11 at 18:18




JSON keys officially should be with surrounded with apices. When you have a JSON object string, it expects you use JSON syntax correctly
– quirimmo
Nov 11 at 18:18












3 Answers
3






active

oldest

votes


















1














there is a difference between javascript object and JSON object, all keys of JSON object must be quoted.



var somestring = "{layers:[{layer1:[17,16,15,14,12]}]}"// not a valid json to parse, it is a normal string, you can use JSON.stringify() to make it a valid json identifiable string.


so the correct JSON string will look like



var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}';
var parsedJson = JSON.parse(somestring)





share|improve this answer





















  • Thanks for the answer! I've accepted this as it addresses the question showing the difference between the two methods - one being JS and one bring JQuery
    – Aphire
    Nov 11 at 19:23



















0














If you change sometring to some of the following examples, it will works.



var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'

var somestring = "{"layers":[{"layer1":[17,16,15,14,12]}]}"


The reason for this is, basically, that's how JSON was specified.



For further examples, take a look at w3schools






share|improve this answer





























    -1














    Best practice is to use JSON.stringify(Object) on one side, and JSON.parse(String) on the other. This will save you many hours of scratching your head over some niggling detail.



    In your example, you could resolve the problem by



    var somestring = JSON.stringify(json)


    For future reference, however, JSON keys must be quoted, so your somestring should be written as:



    var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'


    Good luck!






    share|improve this answer



















    • 3




      JSON strings must be quoted with " not '.
      – Quentin
      Nov 11 at 18:25










    • Haha! See what I mean about niggling details! Fixed.
      – bluejack
      Nov 11 at 20:18













    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53251622%2fcreating-object-from-json-and-parsing-json-different-results%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    there is a difference between javascript object and JSON object, all keys of JSON object must be quoted.



    var somestring = "{layers:[{layer1:[17,16,15,14,12]}]}"// not a valid json to parse, it is a normal string, you can use JSON.stringify() to make it a valid json identifiable string.


    so the correct JSON string will look like



    var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}';
    var parsedJson = JSON.parse(somestring)





    share|improve this answer





















    • Thanks for the answer! I've accepted this as it addresses the question showing the difference between the two methods - one being JS and one bring JQuery
      – Aphire
      Nov 11 at 19:23
















    1














    there is a difference between javascript object and JSON object, all keys of JSON object must be quoted.



    var somestring = "{layers:[{layer1:[17,16,15,14,12]}]}"// not a valid json to parse, it is a normal string, you can use JSON.stringify() to make it a valid json identifiable string.


    so the correct JSON string will look like



    var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}';
    var parsedJson = JSON.parse(somestring)





    share|improve this answer





















    • Thanks for the answer! I've accepted this as it addresses the question showing the difference between the two methods - one being JS and one bring JQuery
      – Aphire
      Nov 11 at 19:23














    1












    1








    1






    there is a difference between javascript object and JSON object, all keys of JSON object must be quoted.



    var somestring = "{layers:[{layer1:[17,16,15,14,12]}]}"// not a valid json to parse, it is a normal string, you can use JSON.stringify() to make it a valid json identifiable string.


    so the correct JSON string will look like



    var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}';
    var parsedJson = JSON.parse(somestring)





    share|improve this answer












    there is a difference between javascript object and JSON object, all keys of JSON object must be quoted.



    var somestring = "{layers:[{layer1:[17,16,15,14,12]}]}"// not a valid json to parse, it is a normal string, you can use JSON.stringify() to make it a valid json identifiable string.


    so the correct JSON string will look like



    var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}';
    var parsedJson = JSON.parse(somestring)






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 11 at 18:48









    Shubham

    16615




    16615












    • Thanks for the answer! I've accepted this as it addresses the question showing the difference between the two methods - one being JS and one bring JQuery
      – Aphire
      Nov 11 at 19:23


















    • Thanks for the answer! I've accepted this as it addresses the question showing the difference between the two methods - one being JS and one bring JQuery
      – Aphire
      Nov 11 at 19:23
















    Thanks for the answer! I've accepted this as it addresses the question showing the difference between the two methods - one being JS and one bring JQuery
    – Aphire
    Nov 11 at 19:23




    Thanks for the answer! I've accepted this as it addresses the question showing the difference between the two methods - one being JS and one bring JQuery
    – Aphire
    Nov 11 at 19:23













    0














    If you change sometring to some of the following examples, it will works.



    var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'

    var somestring = "{"layers":[{"layer1":[17,16,15,14,12]}]}"


    The reason for this is, basically, that's how JSON was specified.



    For further examples, take a look at w3schools






    share|improve this answer


























      0














      If you change sometring to some of the following examples, it will works.



      var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'

      var somestring = "{"layers":[{"layer1":[17,16,15,14,12]}]}"


      The reason for this is, basically, that's how JSON was specified.



      For further examples, take a look at w3schools






      share|improve this answer
























        0












        0








        0






        If you change sometring to some of the following examples, it will works.



        var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'

        var somestring = "{"layers":[{"layer1":[17,16,15,14,12]}]}"


        The reason for this is, basically, that's how JSON was specified.



        For further examples, take a look at w3schools






        share|improve this answer












        If you change sometring to some of the following examples, it will works.



        var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'

        var somestring = "{"layers":[{"layer1":[17,16,15,14,12]}]}"


        The reason for this is, basically, that's how JSON was specified.



        For further examples, take a look at w3schools







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 11 at 18:39









        Kaisen-san

        161




        161























            -1














            Best practice is to use JSON.stringify(Object) on one side, and JSON.parse(String) on the other. This will save you many hours of scratching your head over some niggling detail.



            In your example, you could resolve the problem by



            var somestring = JSON.stringify(json)


            For future reference, however, JSON keys must be quoted, so your somestring should be written as:



            var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'


            Good luck!






            share|improve this answer



















            • 3




              JSON strings must be quoted with " not '.
              – Quentin
              Nov 11 at 18:25










            • Haha! See what I mean about niggling details! Fixed.
              – bluejack
              Nov 11 at 20:18


















            -1














            Best practice is to use JSON.stringify(Object) on one side, and JSON.parse(String) on the other. This will save you many hours of scratching your head over some niggling detail.



            In your example, you could resolve the problem by



            var somestring = JSON.stringify(json)


            For future reference, however, JSON keys must be quoted, so your somestring should be written as:



            var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'


            Good luck!






            share|improve this answer



















            • 3




              JSON strings must be quoted with " not '.
              – Quentin
              Nov 11 at 18:25










            • Haha! See what I mean about niggling details! Fixed.
              – bluejack
              Nov 11 at 20:18
















            -1












            -1








            -1






            Best practice is to use JSON.stringify(Object) on one side, and JSON.parse(String) on the other. This will save you many hours of scratching your head over some niggling detail.



            In your example, you could resolve the problem by



            var somestring = JSON.stringify(json)


            For future reference, however, JSON keys must be quoted, so your somestring should be written as:



            var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'


            Good luck!






            share|improve this answer














            Best practice is to use JSON.stringify(Object) on one side, and JSON.parse(String) on the other. This will save you many hours of scratching your head over some niggling detail.



            In your example, you could resolve the problem by



            var somestring = JSON.stringify(json)


            For future reference, however, JSON keys must be quoted, so your somestring should be written as:



            var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'


            Good luck!







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 11 at 20:17

























            answered Nov 11 at 18:23









            bluejack

            198112




            198112








            • 3




              JSON strings must be quoted with " not '.
              – Quentin
              Nov 11 at 18:25










            • Haha! See what I mean about niggling details! Fixed.
              – bluejack
              Nov 11 at 20:18
















            • 3




              JSON strings must be quoted with " not '.
              – Quentin
              Nov 11 at 18:25










            • Haha! See what I mean about niggling details! Fixed.
              – bluejack
              Nov 11 at 20:18










            3




            3




            JSON strings must be quoted with " not '.
            – Quentin
            Nov 11 at 18:25




            JSON strings must be quoted with " not '.
            – Quentin
            Nov 11 at 18:25












            Haha! See what I mean about niggling details! Fixed.
            – bluejack
            Nov 11 at 20:18






            Haha! See what I mean about niggling details! Fixed.
            – bluejack
            Nov 11 at 20:18




















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53251622%2fcreating-object-from-json-and-parsing-json-different-results%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Full-time equivalent

            Bicuculline

            What is this shape that looks like a rectangle with rounded ends called?