Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

243
Views
How to convert a JSON string to arrays in Javacript

I need a simple help with this question, I'm trying to convert a JSON string to two arrays, look the example:

// What I have
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}'; 


// What I need:
var array1 = {"id":1,"name":"Test1"};
var array2 = {"id":2,"name":"Test2"};

I tried to do it using JSON.parse(str), but with no success like below:

//Works:

var str = '{"id":1,"name":"Test1"}';
dataObj = JSON.parse(str);
console.log(dataObj)

//Doesn't work:

var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
dataObj = JSON.parse(str);
console.log(dataObj)

Any suggestion ?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You haven't properly formatted your JSON string.

It should have been var str = '[{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}]';

about 4 years ago · Juan Pablo Isaza Report

0

all you want to do is put the objects in array

var str = '[{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}]';
dataObj = JSON.parse(str);
console.log(dataObj)

then:

var array1 = dataObj[0];
var array2 = dataObj[1];
about 4 years ago · Juan Pablo Isaza Report

0

Problem is that '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}' isn't valid JSON format.

Try this:

var str = '[{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}]';
dataObj = JSON.parse(str);
console.log(dataObj)

If you want assign objects to two separated variables (as you described):

var obj1 = dataObj[0];
var obj2 = dataObj[1];

I renamed variable names because what is assigned to variable is object, not an array

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!