0

I want to convert the following string to an array

[{id: "1", type: "railroadCrossingSign", latitude: "55.647432", longtitude: "12.187673"}, {id: "2", type: "stationSign", latitude: "55.647444", longtitude: "12.187545"}]

Unfortunately an error occurs when I am JSON.parse(), probably because of the objects in the string...

How do i convert a JSON string with objects to an array with objects?

3 Answers 3

5

JSON format requires that your keys also must be wrapped into "".

var string = '[{"id": "1", "type": "railroadCrossingSign", "latitude": "55.647432", "longtitude": "12.187673"}, {"id": "2", "type": "stationSign", "latitude": "55.647444", "longtitude": "12.187545"}]';

var arr = JSON.parse(string);

console.log(arr);

Sign up to request clarification or add additional context in comments.

Comments

1

In order to achieve what you want. Your JSON key value pair must in a string format too.
Say,

var obj = '[{
  "key" : "value"
}]';

Finally, when you use:

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;  

You get the following results:

John, 30

Comments

0

Some observations :

  • First make sure your JSON should be a valid JSON.
  • Object properties should be wrapped into quotes "".

enter image description here

  • If your JSON is already an JSON Object then no need to parse it again otherwise it will throw an error.

var jsonObj = [{
	"id": "1",
	"type": "railroadCrossingSign",
	"latitude": "55.647432",
	"longtitude": "12.187673"
}, {
	"id": "2",
	"type": "stationSign",
	"latitude": "55.647444",
	"longtitude": "12.187545"
}];

var newObj = JSON.parse(jsonObj);

console.log(newObj); // Error : Uncaught SyntaxError: Unexpected token o in JSON at position 1

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.