How can I parse this string into an array? - javascript

I have a string representation of the following array, generated from Signature Pad:
var myData = "[{lx:47,ly:28,mx:47,my:27},{lx:47,ly:32,mx:47,my:28},{lx:47,ly:40,mx:47,my:32},{lx:48,ly:50,mx:47,my:40},{lx:49,ly:59,mx:48,my:50},{lx:49,ly:66,mx:49,my:59},{lx:51,ly:72,mx:49,my:66},{lx:54,ly:76,mx:51,my:72},{lx:56,ly:76,mx:54,my:76},{lx:58,ly:76,mx:56,my:76},{lx:59,ly:76,mx:58,my:76},{lx:61,ly:76,mx:59,my:76},{lx:62,ly:76,mx:61,my:76},{lx:64,ly:76,mx:62,my:76},{lx:66,ly:73,mx:64,my:76},{lx:70,ly:69,mx:66,my:73},{lx:73,ly:64,mx:70,my:69},{lx:75,ly:61,mx:73,my:64},{lx:79,ly:56,mx:75,my:61},{lx:82,ly:51,mx:79,my:56},{lx:84,ly:46,mx:82,my:51},{lx:85,ly:43,mx:84,my:46},{lx:87,ly:40,mx:85,my:43},{lx:88,ly:35,mx:87,my:40},{lx:90,ly:34,mx:88,my:35},{lx:92,ly:33,mx:90,my:34},{lx:93,ly:32,mx:92,my:33},{lx:94,ly:32,mx:93,my:32},{lx:96,ly:33,mx:94,my:32},{lx:96,ly:35,mx:96,my:33},{lx:99,ly:37,mx:96,my:35},{lx:101,ly:42,mx:99,my:37},{lx:101,ly:46,mx:101,my:42},{lx:101,ly:50,mx:101,my:46},{lx:101,ly:54,mx:101,my:50},{lx:102,ly:57,mx:101,my:54},{lx:104,ly:58,mx:102,my:57},{lx:105,ly:59,mx:104,my:58},{lx:107,ly:60,mx:105,my:59},{lx:108,ly:60,mx:107,my:60},{lx:109,ly:60,mx:108,my:60},{lx:110,ly:60,mx:109,my:60},{lx:112,ly:58,mx:110,my:60},{lx:114,ly:57,mx:112,my:58},{lx:116,ly:54,mx:114,my:57},{lx:119,ly:53,mx:116,my:54},{lx:120,ly:50,mx:119,my:53},{lx:123,ly:49,mx:120,my:50},{lx:127,ly:48,mx:123,my:49},{lx:130,ly:48,mx:127,my:48},{lx:132,ly:48,mx:130,my:48},{lx:134,ly:49,mx:132,my:48},{lx:136,ly:50,mx:134,my:49},{lx:137,ly:52,mx:136,my:50},{lx:139,ly:56,mx:137,my:52},{lx:140,ly:59,mx:139,my:56},{lx:140,ly:60,mx:140,my:59},{lx:143,ly:61,mx:140,my:60},{lx:144,ly:61,mx:143,my:61},{lx:146,ly:61,mx:144,my:61},{lx:151,ly:61,mx:146,my:61},{lx:156,ly:61,mx:151,my:61},{lx:161,ly:61,mx:156,my:61},{lx:167,ly:60,mx:161,my:61},{lx:173,ly:60,mx:167,my:60},{lx:178,ly:60,mx:173,my:60},{lx:185,ly:60,mx:178,my:60},{lx:192,ly:60,mx:185,my:60},{lx:198,ly:60,mx:192,my:60},{lx:207,ly:60,mx:198,my:60},{lx:214,ly:60,mx:207,my:60},{lx:221,ly:60,mx:214,my:60},{lx:226,ly:60,mx:221,my:60},{lx:229,ly:60,mx:226,my:60},{lx:233,ly:60,mx:229,my:60},{lx:234,ly:60,mx:233,my:60},{lx:235,ly:60,mx:234,my:60},{lx:237,ly:60,mx:235,my:60},{lx:238,ly:60,mx:237,my:60},{lx:239,ly:60,mx:238,my:60},{lx:241,ly:60,mx:239,my:60},{lx:244,ly:60,mx:241,my:60},{lx:245,ly:60,mx:244,my:60},{lx:246,ly:60,mx:245,my:60},{lx:248,ly:59,mx:246,my:60},{lx:248,ly:58,mx:248,my:59},{lx:248,ly:57,mx:248,my:58}]";
I tried to convert it to an array:
JSON.parse(myData);
But I get the following error message:
SyntaxError: Unexpected token l
What am I doing wrong? I can't see the mistake:( I tried pasting the exact same data without the quotes in the console and it creates an array:
var myData = [{lx:47,ly:28,mx:47,my:27},{lx:47,ly:32,mx:47,my:28},{lx:47,ly:40,mx:47,my:32},{lx:48,ly:50,mx:47,my:40},{lx:49,ly:59,mx:48,my:50},{lx:49,ly:66,mx:49,my:59},{lx:51,ly:72,mx:49,my:66},{lx:54,ly:76,mx:51,my:72},{lx:56,ly:76,mx:54,my:76},{lx:58,ly:76,mx:56,my:76},{lx:59,ly:76,mx:58,my:76},{lx:61,ly:76,mx:59,my:76},{lx:62,ly:76,mx:61,my:76},{lx:64,ly:76,mx:62,my:76},{lx:66,ly:73,mx:64,my:76},{lx:70,ly:69,mx:66,my:73},{lx:73,ly:64,mx:70,my:69},{lx:75,ly:61,mx:73,my:64},{lx:79,ly:56,mx:75,my:61},{lx:82,ly:51,mx:79,my:56},{lx:84,ly:46,mx:82,my:51},{lx:85,ly:43,mx:84,my:46},{lx:87,ly:40,mx:85,my:43},{lx:88,ly:35,mx:87,my:40},{lx:90,ly:34,mx:88,my:35},{lx:92,ly:33,mx:90,my:34},{lx:93,ly:32,mx:92,my:33},{lx:94,ly:32,mx:93,my:32},{lx:96,ly:33,mx:94,my:32},{lx:96,ly:35,mx:96,my:33},{lx:99,ly:37,mx:96,my:35},{lx:101,ly:42,mx:99,my:37},{lx:101,ly:46,mx:101,my:42},{lx:101,ly:50,mx:101,my:46},{lx:101,ly:54,mx:101,my:50},{lx:102,ly:57,mx:101,my:54},{lx:104,ly:58,mx:102,my:57},{lx:105,ly:59,mx:104,my:58},{lx:107,ly:60,mx:105,my:59},{lx:108,ly:60,mx:107,my:60},{lx:109,ly:60,mx:108,my:60},{lx:110,ly:60,mx:109,my:60},{lx:112,ly:58,mx:110,my:60},{lx:114,ly:57,mx:112,my:58},{lx:116,ly:54,mx:114,my:57},{lx:119,ly:53,mx:116,my:54},{lx:120,ly:50,mx:119,my:53},{lx:123,ly:49,mx:120,my:50},{lx:127,ly:48,mx:123,my:49},{lx:130,ly:48,mx:127,my:48},{lx:132,ly:48,mx:130,my:48},{lx:134,ly:49,mx:132,my:48},{lx:136,ly:50,mx:134,my:49},{lx:137,ly:52,mx:136,my:50},{lx:139,ly:56,mx:137,my:52},{lx:140,ly:59,mx:139,my:56},{lx:140,ly:60,mx:140,my:59},{lx:143,ly:61,mx:140,my:60},{lx:144,ly:61,mx:143,my:61},{lx:146,ly:61,mx:144,my:61},{lx:151,ly:61,mx:146,my:61},{lx:156,ly:61,mx:151,my:61},{lx:161,ly:61,mx:156,my:61},{lx:167,ly:60,mx:161,my:61},{lx:173,ly:60,mx:167,my:60},{lx:178,ly:60,mx:173,my:60},{lx:185,ly:60,mx:178,my:60},{lx:192,ly:60,mx:185,my:60},{lx:198,ly:60,mx:192,my:60},{lx:207,ly:60,mx:198,my:60},{lx:214,ly:60,mx:207,my:60},{lx:221,ly:60,mx:214,my:60},{lx:226,ly:60,mx:221,my:60},{lx:229,ly:60,mx:226,my:60},{lx:233,ly:60,mx:229,my:60},{lx:234,ly:60,mx:233,my:60},{lx:235,ly:60,mx:234,my:60},{lx:237,ly:60,mx:235,my:60},{lx:238,ly:60,mx:237,my:60},{lx:239,ly:60,mx:238,my:60},{lx:241,ly:60,mx:239,my:60},{lx:244,ly:60,mx:241,my:60},{lx:245,ly:60,mx:244,my:60},{lx:246,ly:60,mx:245,my:60},{lx:248,ly:59,mx:246,my:60},{lx:248,ly:58,mx:248,my:59},{lx:248,ly:57,mx:248,my:58}];

Strings are required here. Therefore use "lx" instead of lx
var myData = '[{"lx":47,"ly":28 // and so on

The JSON specification is more strict than JavaScript itself. Specifically, JSON requires all object keys to be enclosed in double quotes. In the JSON spec, an object key must be a string token, and a string token begins and ends with a double quote character.
Thus, you'll need to quote your object keys:
var myData = '[{"lx":47,"ly":28,"mx":47,"my":27},...'
EDIT: According to the Signature Pad API, you can use getSignatureString() to serialize your pad into a valid JSON string.

Your json is not valid. Object property names should be a string so you need to use quotes
var myData = '[{"lx":47,"ly":28 ....}
Visit json.org for more information about this topic

The fact, that your string contains a valid javascript object (note: not JSON object) lets you take advantage of the evil eval function. Just evaluate your string and store its value in a variable like this:
var myData = eval("[{lx:47,ly:28,mx:47,my:27}]");
I made a fiddle for you to see that it works with the string you provided here

the variable myData has incorrect JSON format, to able to use JSON parse you need to add double quotes like here:
var myData = '[{"lx":47,"ly":28,"mx":47,"my":27},...]';

Related

Get the array in a string [javascript]

I need to get the array in the string below:
"['Comedian', 'Actor']"
For example, for the above, I should get ['Comedian', 'Actor'].
Already working using eval(). Is there any other way to get the desired result?
Normally i would suggest using a JSON.parse functionality to do so, however since this is not a valid json format due to single quotes instead of double quotes you could try to first replace those and only then parse
const str = "['Comedian','Actor']";
console.log(JSON.parse(str.replace(/'/g, '"')));
or you could use JSON5
const str = "['Comedian','Actor']";
console.log(JSON5.parse(str));
<script src="https://unpkg.com/json5#^2.0.0/dist/index.min.js"></script>

How to handle JSON string errors (error character ") in javascript

An administrator has directly filled content into the database and formatted it as json string. However, when retrieving it from the database and parse it into json, it failed. Because when filling data directly, instead of content need to write this (\"), they just write (") the json string shield is faulty and cannot parse. How to solve this problem.
Ex:
"aaaa"dddd"aaaa" => "aaaa\"dddd\"aaaa"
I assume that when you retrieve the string from the database, you are getting something like: '"aaaa"dddd"aaaa"'
If so, then you can convert that to a valid JSON string by removing the first and last double quotes and using JSON.stringify to convert the string to a valid JSON string (including escaping the inner double quotes).
For example:
const s = '"aaaa"dddd"aaaa"';
const escaped = JSON.stringify(s.slice(1, -1));
console.log(escaped);
// "aaaa\"dddd\"aaaa"
const parsed = JSON.parse(escaped);
console.log(parsed);
// aaaa"dddd"aaaa
You might use replace with RegExp and g flag
let str = `"aaaa"dddd"aaaa"`;
let result = str.replace(/"/g,`\\"`).slice(1,-2) + '"';
console.log(result)
OP asked My database return result string "aaaa"dddd"aaaa", How to assign such "aaaa"dddd"aaaa"
You can interpolate that return from database into Template Strings
let str = `${database.value}`;
Not sure what database or what language is on server side, however, rather that trying to escape the inner quotes. Trying just replacing the first and last double quote with with a single quote. Not sure of the full context here to know whether this is the issue. Anyway, something to consider

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

How to convert formatted string to regularly javascript dictionary?

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"

JSON array syntax. Are the curly brackets (object syntax) strictly necessary?

Is it possible for a json string to include only square brackets ? For ex. :
[["state","accepted"],["r_by_uid",1]]
I get unexpected character error from parsing that string ... (long time since i worked on this script and i think it worked before ) .
Parsing the json string will allways make an object from the string ? or is it possible to parse the string into an array ?
Basically i just want to parse the string into an array , not an object .
I googled some examples but couldnt find any example that is using only square brackets.
As requested here is the tag that holds the json string :
<button data-fproc='[["state","accepted"],["r_by_uid","1"]]' class="request_state_button">
Curly brackets are not strictly necessary.
[["state","accepted"],["r_by_uid",1]] is valid JSON.
A JSON text can be an object or an array.
See http://json.org/ and the JSON Grammar section in https://www.ietf.org/rfc/rfc4627.txt
You can validate your JSON at http://jsonlint.com/
In Javascript, JSON.parse() returns an array:
JSON.parse('[["state","accepted"],["r_by_uid",1]]')
// result [["state", "accepted"], ["r_by_uid", 1]]
Notice that Arrays are also objects in Javascript.
It works with jQuery.parseJSON() too:
jQuery.parseJSON('[["state","accepted"],["r_by_uid",1]]')
// result [["state", "accepted"], ["r_by_uid", 1]]
Probably this will explain your problem:
var aAsArray = [["state","accepted"],["r_by_uid",1]];
var aAsString = '[["state","accepted"],["r_by_uid",1]]';
​JSON.parse(aAsArray);​​​ //Uncaught SyntaxError: Unexpected token ....
JSON.parse(aAsString);

Categories

Resources