I get formatted json string with all \ before " and \n for newlines.How to convert this string to regularly javascript dictionary ? I thought to replace all \n with '' and \" with " but it is kinda bruteforce solution. Is there moreelegant way ?
-
[`JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) – zzzzBov Feb 20 '14 at 21:21
4 Answers
It sounds like you're receiving JSON encoded data. To convert the raw data into an object, use the JSON.parse
function:
var test = "{\"foo\":\"bar\"}";
var data = JSON.parse(test);
console.log(data);

- 174,988
- 54
- 320
- 367
I am not sure I understand what you mean by 'JavaScript dictionary' exactly but in my experience the easiest way to convert a JSON string to any kind of usable JavaScript object is to use JSON.parse, see Parse JSON in JavaScript? for some good information on this.
Also in future a small sample of what you are trying to do, your source data etc. would be helpful!

- 1
- 1

- 36
- 3
It's a escaped string, you should unescape it and using eval will return the object represented by the json string. A JSON string is simply a javascript serialized object, so you may eval'd with javascript and will return the "map" or object that represents. Newlines are valid in json so you don't require to remove them.
var o = eval("o = {name:\"test\"}");
alert(o.name);

- 809
- 9
- 15
You're probably thinking of a dictionary implementation as you'd find in other languages such as Objective C or C# - JavaScript does not have a dictionary implementation. So is your question how to parse JSON so you can get some values into key value pairs? If so then it sounds like JSON.parse is going to work for you.
If your question is about how to implement something like a dictionary in JavaScript, with data populated from JSON - then you'll want to parse the JSON and set up some simple JavaScript objects to act like a dictionary:
var dictionary = {"key1":"hello", "key2":"hello2", "key3":"hello3"};
console.log(dictionary["key3"]); // gives the value "hello3"

- 58
- 1
- 5