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" ];
3
  • 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. Commented Jun 3, 2013 at 20:03
  • YES I want to convert it into JSON array, for example code type1 type2 type3. Commented Jun 3, 2013 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. Commented Jun 3, 2013 at 20:06

3 Answers 3

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(', ');
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Ok, how would i do it for this? stackoverflow.com/questions/16904286/…
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.