Owais p
Owais p

Reputation: 109

how convert string to object in javaScript

i have used Object.parses() but getting error

var obj = '
   "users": [
 { "name":"John", "age":30, "city":"New York"},
 { "name":"Mike", "age":25, "city":"new jersey"},   
]'

Upvotes: 1

Views: 18235

Answers (2)

ADyson
ADyson

Reputation: 61849

Although you haven't mentioned JSON explicitly, this data looks like JSON. You can use JSON.parse() to turn JSON strings into JavaScript variables

However, the string you've posted isn't actually valid JSON because of a couple of syntax errors. You can fix those to get (what I assume is) the intended object structure:

1) remove the extra double-quote before new jersey

2) add curly braces at either end to make it into a valid object.

3) remove extra comma after the last array entry (although a lot of parsers will tolerate this in fact)

So you end up with

{ 
  "users": [
    { "name":"John", "age":30, "city":"New York"},
    { "name":"Mike", "age":25, "city":"new jersey"}
  ]
}

And this can be parsed easily:

var obj = '{ "users": [{    "name": "John",    "age": 30,    "city": "New York"  },  {    "name": "Mike",    "age": 25,    "city": "new jersey"  }]}';

var data = JSON.parse(obj);

console.log(data);
console.log("----------");

//example of gettng a specific property, now it's a JS variable
console.log(data.users[0].name);

Upvotes: 5

Yuri
Yuri

Reputation: 2900

First, correct your string. It should look like on inserted snippet. Second, use JSON.parse()

var t = '{"users": [{ "name":"John", "age":30, "city":"New York"},{ "name":"Mike", "age":25, "city":"new jersey"}]}'; 
    
     
     var obj = JSON.parse(t);
     console.log(obj["users"][0].name);
     console.log(obj["users"][0].age);
     console.log(obj["users"][0].city);

Upvotes: 1

Related Questions