1

Possible Duplicate:
Convert Javascript Array to JSON

I am trying to figure out how to return an array and store it in json variable as string, is that possible? [If not, how can I return all the outputs and store it json?] - If you know what I mean...

    //arr = ["a", "b", "c", "d", "ddd"]
    //largest = 3
    var generateEntryCodes = function(arr, largest) {
        var newText = ""
        for(var i=0; i < arr.length; i++) {
            if (arr[i] == null) {
                arr.splice(i, 1);
                i--;
            }
            var counts = arr[i].length != largest ? (parseInt(largest) - parseInt(arr[i].length)) : 0
            for (var z=0; z<counts;z++)
                newText += "0"
            var result = arr[i].splice( 0, 0, newText )
            newText = ""
            result = [{
                "result": result, 
                "total": result.length
            }]
        }
        return result
    }

I am try to output the above code as:

00a
00b
00c
00d
ddd

But as I flash the result json. I only get "ddd"... So I tried adding before the result = [{}] jSON code:

$("textarea").val( $("textarea").val("") + result + "\n")
//outputs:
   00a
   00b
   00c
   00d
   ddd

How can I get all the outputs from result variable and store it in JSON variable.

Problem: Code only store into JSON the last array.

Community
  • 1
  • 1
Peter Wateber
  • 3,824
  • 4
  • 21
  • 26
  • possible duplicate of [Convert Javascript Array to JSON](http://stackoverflow.com/questions/2295496/convert-javascript-array-to-json) and [Convert JS object to JSON string](http://stackoverflow.com/questions/4162749/convert-js-object-to-json-string). – Felix Kling Oct 06 '12 at 07:16

2 Answers2

6

Generally speaking you can simply construct your JavaScript object and then serialize it to JSON like in the example below:

var myArray = ['a','b','c'];
var jsonString = JSON.stringify(myArray);

That should work. Note that you might have to include JSON2.js in case your browser doesn't support it natively.

//Edit:
That should work: http://jsbin.com/welcome/31083/edit

Here's the code:

var generateEntryCodes = function(arr, largest) {
        var newText = "",
            codes = [],
            currentElement,
            result;


        for(var i=0; i < arr.length; i++) {
          currentElement = arr[i];

          var zerosToPrepend = largest - currentElement.length;
          for (var z = 0; z < zerosToPrepend; z++){
                newText += "0"
          }

          currentElement = newText + currentElement;
          codes.push(currentElement);    

          newText = ""
        }

      result = {
        codes: codes,
        total: codes.length
      };

        return result
    }


var result = generateEntryCodes(["a", "b", "c", "d", "ddd"], 3);
console.log(result);

This should return a JavaScript object that looks as follows:

{"codes": ["00a", "00b", "00c", "00d", "ddd"], "total": 5}

You can then take that result and use JSON.stringify(...) to convert it into a JSON string.

Juri
  • 32,424
  • 20
  • 102
  • 136
  • Thanks mate but the **result** variable is not an array but only set of strings: "00a 00b 00c 00d ddd" – Peter Wateber Oct 06 '12 at 06:56
  • Then you could do a `result.split(' ')` which would again give you an array. But it's better to modify your `generateEntryCodes` function then. – Juri Oct 06 '12 at 06:59
  • Sorry its not "{" its "[" my bad. I tried using split("\n") since the code var result = arr[i].splice( 0, 0, newText ) outputs "00a 00b 00c 00d" (per row)... please try to run the code – Peter Wateber Oct 06 '12 at 07:00
  • Hmm...I'd revision the function as I spot quite some errors there. What is the purpose you'd like to achieve with it?? And what's the result you'd expect? – Juri Oct 06 '12 at 07:04
  • I would want to have the json result variable as Array => result: "00a 00b 00c 00d ddd", total: 5 – Peter Wateber Oct 06 '12 at 07:06
  • @Peter: `return JSON.stringify(result);` ? – Felix Kling Oct 06 '12 at 07:09
  • @FelixKling I already tried that mate. Please try to run the code. – Peter Wateber Oct 06 '12 at 07:10
  • @PeterWateber Edited my post with a modified version of the code. Plz try it – Juri Oct 06 '12 at 07:15
  • @Peter: Well, there might be other errors in your code. When I run it, I get `Uncaught TypeError: Object a has no method 'splice' `. But you got and answer to your question, use `JSON.stringify` to serialise JS objects and errors to JSON. – Felix Kling Oct 06 '12 at 07:15
  • @FelixKling as for the splice String.prototype.splice = function( idx, rem, s ) { return (this.slice(0,idx) + s + this.slice(idx + Math.abs(rem))); } – Peter Wateber Oct 06 '12 at 07:20
  • @PeterWateber Sure, but you didn't include that in your code sample, so people were not able to run it and hence help you more easily :) Plz take a look at how I structured the code, you initialized the `result` variable each time in the loop wherefore the code didn't work properly. Moreover you created the result within the for loop. The only reason why this code even worked is because you just met JavaScript's variable hoisting ;) – Juri Oct 06 '12 at 07:22
  • Thanks you so much mate! Base from my code, I even to put the result variable outside the loop but still it gives me the same output... Apparently, this so much of great help! Many thanks man! I see what you did there!! – Peter Wateber Oct 06 '12 at 07:24
1

if you have string like aaa bbb ccc than first convert it into array

var str="aaa bbb ccc ddd";
var n=str.split(" ");

Now can use JSON.stringify(string) to convert string into json

var myjson=JSON.stringify(n);
Juri
  • 32,424
  • 20
  • 102
  • 136
StaticVariable
  • 5,253
  • 4
  • 23
  • 45