1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

JSON stringify is not converting array to string

Discussion in 'JavaScript' started by JEET, May 15, 2020.

  1. #1
    JSON stringify is not converting array to string

    I am trying to convert a js array to json string. The array has "string" keys. JSON.stringify is not converting the array to string.

    This is my code.


    a=new Array();
    a["k1"]="apple";
    a["k2"]="berry";

    t= JSON.stringify(a);
    console.log(t);

    //writes an empty [] to console.
     
    Solved! View solution.
    JEET, May 15, 2020 IP
  2. hdewantara

    hdewantara Well-Known Member

    Messages:
    536
    Likes Received:
    47
    Best Answers:
    25
    Trophy Points:
    155
    #2
    Hi JEET,
    As far as I can remember, a["k1"]="apple" is an assignment for object property and so is the same as calling a.k1 = 'apple'.
    So... I guess this "a" object should be initialized as a = {} instead of a = []
     
    hdewantara, May 15, 2020 IP
    JEET likes this.
  3. JEET

    JEET Notable Member

    Messages:
    3,825
    Likes Received:
    502
    Best Answers:
    19
    Trophy Points:
    265
    #3
    Hi, @hdewantara
    a["k1"]="value" works for both arrays and objects, only the declaration decides if "a" will be an object or array.

    Anyways, I dropped the idea of using JSON. Going with sending array parameters as URL querystring instead. That worked fine.
    Thanks
     
    JEET, May 15, 2020 IP
  4. #4
    If you're trying to turn it into json to send as data in an ajax request just let jquery do it and create the data array.

    Something from what I've been working on.

    
    let sData = {
                            'lat': coord.lat,
                            'lng' : coord.lng,
                            'photo': p.options.data.image,
                            'name' : p.options.data.title
                        };
                       window.plugin.savep.saveList.push(sData);
                    
                    $.ajax({
                            dataType: "json",
                            url: 'https://www.mysite.com/saveBatch.php',
                            data: window.plugin.savep.saveList,
                            success: function(rData){
                                //console.log(rData);
                            }
                        });
    Code (javascript):
     
    Last edited: May 15, 2020
    sarahk, May 15, 2020 IP
    JEET likes this.
  5. JEET

    JEET Notable Member

    Messages:
    3,825
    Likes Received:
    502
    Best Answers:
    19
    Trophy Points:
    265
    #5
    JEET, May 15, 2020 IP
  6. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #6
    Last I knew? No, it doesn't. JavaScript cannot do associative Arrays. This isn't PHP. It indexes MUST be numeric, and even then they're DISCARDED.

    var a = [];
    a[4] = 10;
    a[9] = 11;
    console.log(a[0]); // outputs 10
    console.log(a[1]); // outputs 11
    console.log(a[4]); // outputs undefined
    console.log(a[9]); // outputs undefined
    Code (markup):
    JavaScript arrays CANNOT have named indexes, nor do they MAINTAIN indexes, they ALWAYS condense starting at zero regardless of what index you use. Just as if you remove an element from the middle of the Array everything "above" it gets shifted down one index.

    HOWEVER, your command does put those values on it, but they are there as non-iterable properties of the Array OBJECT, NOT part of the Array's VALUES.

    	var a = [];
    	a['k11'] = 10;
    	a['k19'] = 20;
    	console.log(a);
    Code (markup):
    Outputs:
    Array []
    k11: 10
    k19: 20
    length: 0
    <prototype>: Array []
    Code (markup):
    See that ZERO length? You added them to the object that handles the array, and not the array itself. Big difference. They are NOT array iterable declared that way.

    This is because JavaScript arrays are NOT Arrays, they're pointered lists. Also this is 2020 not 1998, you can stop saying Array(); as we stopped caring about Netscape 4 a decade and a half ago.

    And FFS @sarahk, "just let jQuery do it" is NOT the bloody answer!
     
    deathshadow, May 16, 2020 IP
  7. JEET

    JEET Notable Member

    Messages:
    3,825
    Likes Received:
    502
    Best Answers:
    19
    Trophy Points:
    265
    #7
    @deathshadow
    "Only numerical indexes in javascript" used to be true, not any more.
    Javascript arrays can have string indexes these days, and work very much like objects.
    Try this:

    a= [];
    //or this
    //a=new Array();
    //either is fine

    a["k"]="ok";
    console.log(a["k"]);

    //outputs "ok" in console.

    I have already written a whole page around this, with multidimensional arrays, works fine.
    I will post in review section once done.
    Thanks
     
    JEET, May 16, 2020 IP
  8. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #8
    Just because you can access it that way does NOT mean it's part of the "array". That's not how this works. YES, it's there. You can see that in my console output, but what you've done is attached the value to the OBJECT and not the members of the Array.

    You can do the same thing to a String!

    a = 'this is a test';
    a['k'] = 'not part of the string';
    console.log(a['k']);

    As such any function that you want to treat the array as an iterable will completely ignore those properties you attached.

    It's no different than doing:

    a = ['one', 'two', 'three'];
    a['output'] = function() {
      for (var i of a) console.log(i);
    };
    a.output();
    Code (markup):
    Will output one, two, three. The output METHOD is not part of the array any more than the PROPERTIES you are putting on the Array OBJECT. They are not in any way, shape, or form part of the array itself. Hence why Array.length would be three in this previous test, and again notice that the Array.length is ZERO in my previous post.

    You are NOT adding the values to the array in a manner by which ANY Array method -- find, indexOf, foreach, reduce, map, shift, sort -- are going to find them because they're NOT part of the array, they're part of the object interface TO the array, based on the prototype object named Array, which is descended from Object.

    Hence the difference between an array and the Array object, and why with most JS objects we use the capital letter distinction to differentiate between what it does, and what it is. You can have an object, it inherits from Object. That cap letter means something.

    You're SO far off the mark it's going to bite you sooner than later. In fact it likely already has. You want an "associative" array PHP style, you have to use an object if you want to iterate it, using (var i in Object). You're getting the Array object, not the array the object accesses.

    
    var a = [];
    a[k] = 47;
    a[r] = 15;
    console.log(a.length); // ZERO! Nada, zip, zilch, nein!
    
    Code (markup):
    They're not in the array, they are properties of the Array object instance. Hence why JSON.parse can't see them either. They're not in the array, they're ON the Array object. No more than for/of, Array.forEach, Array.sort, or any other actual Array method would.
     
    Last edited: May 16, 2020
    deathshadow, May 16, 2020 IP
    JEET likes this.
  9. JEET

    JEET Notable Member

    Messages:
    3,825
    Likes Received:
    502
    Best Answers:
    19
    Trophy Points:
    265
    #9
    Hmm... I get your point now.

    a["k"]="ok";
    console.log(a);
    //shows empty array

    a[0]="ok";
    console.log(a);
    //sshows array with value

    Wish I knew this difference earlier, would have saved me a lot of time.
    Thanks @deathshadow
     
    JEET, May 16, 2020 IP
  10. JEET

    JEET Notable Member

    Messages:
    3,825
    Likes Received:
    502
    Best Answers:
    19
    Trophy Points:
    265
    #10
    Changed the whole code to use objects instead of array, and JSON.stringify also worked.
     
    JEET, May 16, 2020 IP
    sarahk likes this.