0

How to insert text into json array using jquery/javascript .

supposing I have data as

some numbercodes in a text file format 123, 456, 789

I want to get them in a json array format using javascript/jquery.

var nuumbercodes = [ "123","456","789" ];
Davide Pastore
  • 8,678
  • 10
  • 39
  • 53
patz
  • 1,306
  • 4
  • 25
  • 42
  • 4
    I don't see any JSON. That's a JavaScript array. Do you want to convert `nuumbercodes` to JSON? You certainly don't want to directly modify JSON with JavaScript. You parse it, modify the data structure and serialize it back. – Felix Kling Jun 03 '13 at 20:03
  • YES I want to convert it into JSON array, for example code type1 type2 type3. – patz Jun 03 '13 at 20:06
  • There is some serious confusion with the terminology here. `["123","456","789" ]` is a javascript Array. `JSON`(JavaScript Object Notation) is just a string notation of an Object. – Selvakumar Arumugam Jun 03 '13 at 20:06

3 Answers3

1

If you have a well formatted text string with comma separated numbers,
like this '123,456,789'

This should have no spaces or tabs,
Then you can convert it simply into a JavaScript array.

var myTextwithNuumbercodes='123,456,789';

var numbercodes=myTextwithNuumbercodes.split(',');

returns ['123','456','789']

if you have a JSON string like this '[123,456,789]' then you get a javascript array by calling JSON.parse(theJSONString)

var numbercodes=JSON.parse('[123,456,789]');

returns [123,456,789]

notice the "[]" in the string ... that is how you pass a JSON array toconvert it back to a string you can use JSON.stringify(numbercodes);

if you have a total messed up text then it's hard to convert it into a javascript array but you can try with something like that

var numbercodes='123, 456, 789'.replace(/\s+/g,'').split(',');

this firstly removes the spaces between the numbers and commas and then splits it into a javascript array

in the first and last case you get a array of strings u can transform this strings into numbers by simply adding a + infront of them if you call them like

mynumbercode0=(+numbercodes[0]);// () not needed here ...

in the 2nd case you get numbers

if you want to convert an array to a string you can also use join();

[123,456,789].join(', ');
Zach
  • 539
  • 1
  • 4
  • 22
cocco
  • 16,442
  • 7
  • 62
  • 77
0

Assuming your data is in a string, then split it on commas, use parseInt in a for loop to convert the string numbers into actual Numbers and remove the whitespace, then JSON.stringify to convert to JSON.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Ok, how would i do it for this? http://stackoverflow.com/questions/16904286/put-data-from-textarea-into-json-array – patz Jun 03 '13 at 20:15
0

You could use .push() push values at the end of an array. After that you could use JSON.stringify(nuumbercodes) to make a JSON string representation of your Array.

Thomas Junk
  • 5,588
  • 2
  • 30
  • 43