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

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

Related

JSON Parse with square brackets inside data

I am trying to parse a JSON string which contains square brackets inside the string.
For example
"[[\"hello\", \"i\", \"like [cows]\"], [\"what\", \"about [you]?\"]]"
It shows an error while parsing:
Uncaught SyntaxError: Unexpected token [
How can I parse the string anyway while leaving the brackets as they are?
I found the problem. I needed to use addslashes() around the strings in the PHP code which serves the code. There was a part of a string containing [C:\].
I see in your later comments that you're creating this JSON string within PHP. You should encode the JSON data within PHP using json_encode, as shown here:
http://www.dyn-web.com/tutorials/php-js/json/array.php
It should then come out in a format that you can JSON.parse.

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

Handling backslash when parsing json

Here is a portion of a larger JSON string that I attempting to call JSON.parse on. I am getting the infamous 'invalid character' error because (I believe) of the backslash parentheses (ie. "path:\"https://mysite.sharepoint.com/sites/Test\").
All online parsers I have tried it on works fine but in my javascript code the JSON.parse method fails.
I have attempted to clean the string like this and other ways but I have been unable to get it to parse.
var cleanData = data.replace(/\\"/, /\\\\/);
below is the partial JSON file. When I remove it from the JSON string the JSON.parse works so I think I have this isolated to just this. What type of general purpose clean method would work to get this thing to parse? Thansk
'{"Properties" : {
"GenerationId" : 9223372036854776000,
"indexSystem" : "",
"ExecutionTimeMs" : 109,
"QueryModification" : "path:\"https://mysite.sharepoint.com/sites/Test\" (IsDocument:\"True\" OR contentclass:\"STS_ListItem\") ContentTypeId:0x0120D5200098CBB075E51C8C4398ECCB4B4928912D*",
"RenderTemplateId" : "~sitecollection/_catalogs/masterpage/Display Templates/Search/Group_Default.js",
"StartRecord" : 0,
"piPageImpressionBlockType" : 2
}}
how?
The problem is that your backslash is getting swallowed as an escape character in the string:
'\"' === '"' // true
You actually need to escape the backslashes, so that the JSON parser sees them. Here's another example:
var unencoded = 'string with "quotes"';
'"string with \"quotes\""' === JSON.stringify(unencoded); // false
'"string with \\"quotes\\""' === JSON.stringify(unencoded); // true
However, where the escaping should be done depends on how the JSON is being made available to the JavaScript. If the JSON is embedded in the page by a server-side script, then there's no need to use JSON.parse, as valid JSON is valid JavaScript:
// if JsonData is valid JSON, it's also a valid JavaScript object
var data = <%= JsonData %>;

Javascript - strip out occurrences of u' in JSON string, parse is returning unexpected token

I have a textfield in a database that contains the results of a python json.dumps(list_instance) operation. As such, the internal fields have a u' prefix, and break the browser's JSON.parse() function.
An example of the JSON string is
"density": "{u'Penobscot': 40.75222856500098, u'Sagadahoc':
122.27083333333333, u'Lincoln': 67.97977755308392, u'Kennebec':
123.12237174095878, u'Waldo': 48.02117802779616, u'Cumberland':
288.9285325791363, u'Piscataquis': 3.9373586457405247, u'Hancock':
30.698239582715903, u'Washington': 12.368718341168325, u'Aroostook':
10.827378163074039, u'York': 183.47612497543722, u'Franklin':
16.89330963710371, u'Oxford': 25.171240748402518, u'Somerset':
12.425648288323485, u'Knox': 108.48302300109529, u'Androscoggin':
208.75502815768303}"
What I'd like to do is replace those occurrences of u' with a '(single-quote). I've tried
function renderValues(data){
var pop = JSON.parse(data.density.replace(/u'/g, "'"));
}
but I'm always getting a unexpected token ' exception. Since many of the possible key fields may contain a u, it is not feasable to just delete that character. How can I find all instances of u' and replace with ' without getting the exception?
The accepted solution is wrong. Your code fails because that string is not valid JSON. Fixing the pseudo-JSON string by replacing it is wrong.
What you have to do is fix the python code that is producing that broken JSON string, which I am pretty sure it is a str() or unicode() where there should be nothing. What you have as a value for the key "density" is a string instead of a dictionary, and therefore, python returns you something like the following:
{"density": "a string that looks like JSON but it is in fact a string reprensentation of a dictionary"}
The function json.dumps will return you always valid JSON strings.
Fix that and you will not have to hack around with filthy string replacements or whatever.
EDIT
Check the following snippet out. There you can see that the u'...' is just the python readable-representation of a unicode object, and has nothing to do whatsoever with a JSON serialization.
>>> import json
>>> data = {u'name': u'Manuel', u'age': 26}
>>> print data
{u'age': 26, u'name': u'Manuel'} # this is the python representation of a dictionary
>>> print json.dumps(data)
{"age": 26, "name": "Manuel"} # this is a valid JSON string
That JSON is not properly formed, as easy as that.
Updated solution: replace(/u'/g, "'")); => replace(/u'(?=[^:]+')/g, "'"));.
Tested with the following:
"{u'Penobscot': 40.75222856500098, u'Sagadahoc': 122.27083333333333, u'Lincoln': 67.97977755308392, u'Kennebec': 123.12237174095878, u'Waldo': 48.02117802779616, u'Cumberland': 288.9285325791363, u'Piscataquis': 3.9373586457405247, u'Hancock': 30.698239582715903, u'Timbuktu': 12.368718341168325, u'Aroostook': 10.827378163074039, u'York': 183.47612497543722, u'Franklin': 16.89330963710371, u'Oxford': 25.171240748402518, u'Somerset': 12.425648288323485, u'Knox': 108.48302300109529, u'Androscoggin': 208.75502815768303}".replace(/u'(?=[^:]+')/g, "'");
results in:
"{'Penobscot': 40.75222856500098, 'Sagadahoc': 122.27083333333333, 'Lincoln': 67.97977755308392, 'Kennebec': 123.12237174095878, 'Waldo': 48.02117802779616, 'Cumberland': 288.9285325791363, 'Piscataquis': 3.9373586457405247, 'Hancock': 30.698239582715903, 'Timbuktu': 12.368718341168325, 'Aroostook': 10.827378163074039, 'York': 183.47612497543722, 'Franklin': 16.89330963710371, 'Oxford': 25.171240748402518, 'Somerset': 12.425648288323485, 'Knox': 108.48302300109529, 'Androscoggin': 208.75502815768303}"
a little bit old in the answer but if there is no way to change or access the server response try with:
var strExample = {'att1':u'something with u'};
strExample.replace(/u'[\}|\,]/g, "ç'").replace(/u'/g, "'").replace(/ç'/g, "u'");
//{'att1':'something with u'};
The first replace will handle the u' that are in the trailing part of the string in the object changing it to 'ç' character
then removing the u from the phyton unicode and finally change it to u' like the original
I had a similar issue and made this regex that found all of the u's even if the values had them too.
replace(/(?!\s|:)((u)(?='))/g, "")
The accepted answer, I found, missed these occurrences.
I know the OP's doesn't have 'u' for the values and only for keys but thought this may be useful too :)

How can I parse this string into an array?

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},...]';

Categories

Resources