How to convert formatted string to regularly javascript dictionary? - javascript

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 ?

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);

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!

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);

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"

Related

parse a string that contains array with strings

I am struggling to parse a string that contains array. And the array also contains list of arrays.
Each of the array contains string.
code here
let a = "[[48934, 'Danial Brendon', 'developer'],[48934, 'Nicki Lopez', 'developer']]";
console.log(JSON.parse(a))
I tried using JSON.parse() but did not work, may be because JSON.parse() also want to parse the string.
I am having difficulty with this even this looks simple. I could not find any similar question/answer like this.
Thanks.
To JSON parse , you need double quotes instead of single. like this ...
let a = '[[48934, "Danial Brendon", "developer"],[48934, "Nicki Lopez", "developer"]]';
console.log(JSON.parse(a));

Convert String of certain format to JSON in javascript

I have a string of the format
var str = "{key1=value1, Key2=value2}"
I need to convert this into a json object to be able to iterate through it.
Any suggestions on how this can be done? there can be any number of keys
You need first to "JSONize" this string you are getting so it can be converted to a JavaScript object using the JSON class. My guess, if the string has always this format ({key=value, ...}), is that you could parse it first like this:
var parsedString = yourString.replace(/(\b\S+\b)=(\b\S+\b)/g, '"$1":"$2"')
This way, from this: "{key1=value1, Key2=value2}" you get this: '{"key1":"value1", "Key2":"value2"}'.
Then, as someone suggested, just use JSON.parse(parsedString) to get your JS object.

correctly adding to json from javascript

hi im having trouble correctly adding to my json
here is the code.
When i console.log the string im trying to add is
{"type":"#","name":"wh2xogvi","list":[{"0":"background-color"},{"1":"border"},{"2":"width"}, {"3":"height"},{"4":"margin"}],"listvalues":[{"0":"#aaa"},{"1":"2px solid #000"},{"2":"1040px"},{"3":"50px"},{"4":"0 auto"}]}
it is valid json
var jsonltoload = JSON.stringify(eval("(" + jsonloadtostring + ")"));
console.log(jsonltoload); // this is the console log i was talking about higher up
fullJSON.styles.objectcss.push(jsonltoload);
But when i actually look at the json it is wrong ends up something like this
"{\"type\":\"#\",\"name\":\"unkd42t9\",\"list\":[{\"0\":\"background-color\"},{\"1\":\"border\"},{\"2\":\"width\"},{\"3\":\"height\"},{\"4\":\"clear\"}],\"listvalues\":[{\"0\":\"#ddd\"},{\"1\":\"2px solid #000\"},{\"2\":\"100%\"},{\"3\":\"50px\"},{\"4\":\"both\"}]}",
the fullJSON comes from JSON.parse(json); which comes from a file
You seem to confuse JSON, a textual, language-independent data representation, with JavaScript objects, a language-specific data type.
JSON.stringify returns a string (containing JSON), so jsonltoload is a string. I guess you simply want to parse the JSON and add the resulting object:
var obj = JSON.parse(jsonloadtostring);
fullJSON.styles.objectcss.push(obj);
I think the JSON string is trying to escape the double quotes character you have added to string, resulting in the string. try to enclose the whole string with single quotes rather than double quotes

Using javascript objects with UTF-16 property names

I'm calling a service that returns UTF-16 json data.
My question is if the JSON object has UTF-16 strings as property names is there a simple way to reference these properties?
For example, here is how the response data looks like after calling JSON.stringify on it:
"{"C\u0000o\u0000n\u0000t\u0000e\u0000n\u0000t\u0000s\u0000":{ ...
In my code I'd like to do something like data['Contents']. Is there a simple way around this that avoids either hardcoding the strings with unicode escape sequences?
Update: changed to indicate strings are UTF-16.
Here's an example (Visual C++) of the call to generate the JSON output:
wchar_t* str = _T("Contents");
yajl_gen_string(g, (unsigned char*)str, wcslen(str) * sizeof(TCHAR));

convert a structured string into array

this question might have been asked already. But i really have no idea what to search for.
If I have a string like
{{aa:bb,aaa:bbb,cc:ee{{aa:cd,cdc:dd,{{ss:ee}},kk:ee}},se:ff}}
I need to get output in probably in array
ar[0] = aa:bb, ar[1]=aaa:bbb, ar[3] = {{...}}
I tried using variable.split("}}")
which is breaking the string and not getting the actual data.
Is there any recursive function to do this?
I am not able to search because I have no clear idea of what objects,strings.
If you used an existing format for structuring your string, such as JSON:
["aa:bb","aaa:bbb","cc:ee",["aa:cd","cdc:dd",["ss:ee"],"kk:ee"],"se:ff"]
Then you could just run it through JSON.parse(). - It'd be far easier than trying to decode the meaning of that string without being told what it means.
I think what you're looking for is how to parse a JSON string into an object. I'm not certain, but at least it looks like that based on the format of your string. Can you confirm if the source is providing JSON output?
If yes:
Read this other SO question.

Categories

Resources