This is my first time to convert JSON data with jQuery however, I get the following error when I try to convert the JSON string. Am I doing something wrong? I was searching for some simple sites about converting JSON string in jQuery, but most of the tutorial seems a bit difficult to understand. I would love to here some tips about converting jsons from url with jQuery if possible.
var obj = jQuery.parseJSON( '{"result":[{"id":"25","name":"loplo\n","score":"1198"},{"id":"58","name":"adjm","score":"1131"},{"id":"60","name":"dragon with ","score":"1083"},{"id":"57","name":"tDj","score":"799"},{"id":"59","name":"dragon with ","score":"452"},{"id":"55","name":"Donny","score":"450"},{"id":"56","name":"ajo ","score":"401"},{"id":"61","name":"make ","score":"392"}]}' );
Error message
Uncaught SyntaxError: Unexpected token
in JSON at position 35
at JSON.parse (<anonymous>)
at Function.m.parseJSON (jquery-1.11.1.min.js:4)
at leaderboard.js:16
The reason you're getting that error message is the \n in the first element that has the name: "loplo\n"
This is because new lines are allowed in JSON objects like that as they need to be either removed or escaped.
To get around this you can do
var obj = jQuery.parseJSON(mystring.replace(/\n/g,"\\n"));
You can read more about this here:https://bugs.chromium.org/p/v8/issues/detail?id=616
This is because you have the new line character as the value of loplo:
"loplo\n"
Remove the \n and it should work.
I don't recommend removing all of the \n with replace because you may want that. If you want to keep the \n, add a escape character before it, like this:
"loplo\\n" and it should work.
use this...
var e = '{"result":[{"id":"1351","identite":"RES ADDS","etat":"1","email":"udohou#gmail.com","telephone":"8787878","adresse":"COTONOU","nom_pays":"Togo","indicatif":"228"},{"id":"1350","identite":"MY DREAM","etat":"2","email":"dohouulrich#gmail.com","telephone":"5248525","adresse":"COTONOU","nom_pays":"Togo","indicatif":"228"},{"id":"1349","identite":"UN ","etat":"1","email":"dohouulrich#gmail.com","telephone":"66353364","adresse":"","nom_pays":"Benin","indicatif":"229"},{"id":"1348","identite":"DOHOU ULRICH SEMASSA & Fils","etat":"1","email":"dohouulrich#gmail.com","telephone":"66353364","adresse":"COTONOU","nom_pays":"Benin","indicatif":"229"},{"id":"1344","identite":"DC","etat":"2","email":"dohouulrich#gmail.com","telephone":"66353364","adresse":"","nom_pays":"Afghanistan","indicatif":"93"},{"id":"1343","identite":"AGAIN","etat":"2","email":"dohouulrich#gmail.com","telephone":"66353364","adresse":"","nom_pays":"Afghanistan","indicatif":"93"},{"id":"1342","identite":"SOCIAL LIMITED","etat":"3","email":"dohouulrich#gmail.com","telephone":"66353364","adresse":"","nom_pays":"Afghanistan","indicatif":"93"}]}';
var json = JSON.stringify(eval('(' + e + ')'));
var arr = $.parseJSON(json);
var resultData = arr['result'] ;
console.log(resultData) ;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I changed the Json String data because yours was not working. I think it is not well formated
Related
I've a string
var my_str="[(0,10),(1,15),(2,48),(3,63),(4,25),(5,95),(6,41),(7,31),(8,5),(15,2)]";
I need to convert it into an array of list. For example,
alert(my_str[1])
would give an output of 1,15.
I've tried the following:
var myarray = JSON.parse(my_str);
but it throws the error "unexpected token ( in JSON at position 1"
I tried this
var myarray = JSON.parse(my_str);
but it throws error "unexpected token ( in JSON at position 1"
So I changed the structure of my string to:
var my_str="[[0,10],[1,15],[2,48],[3,63],[4,25],[5,95],[6,41],[7,31],[8,5],[15,2]]";
That worked like a charm ;)
The problem is that you are using a strange sintax for delimiting inner objects. It would be appropriate to use "[" and "]" instead of "(" and ")".
Anyway you can easily replace them with javascript and make your structure an array of arrays of strings. Sounds a bit creepy, but this way you can create a licit JSON object and benefit of JS native methods.
var my_array = JSON.parse(my_str.replace(/\(/g,'[').replace(/\)/g,']'))
you can now work on my_array object and retrieve couples of numbers using array indexes
my_array[1] ---> 1,15
You have to replace ( by '( and ) by )' ,, then , apply eval :
eval(arr.replace(/(/g,'\'(').replace(/)/g,')\''));
//> ["(0,10)", "(1,15)", "(2,48)", "(3,63)", "(4,25)", "(5,95)", "(6,41)", "(7,31)", "(8,5)", "(15,2)"]
This is a pretty naive idea, but does work (without JSON.parse or eval):
var arr = my_str.replace('[(', '').replace(')]', '').split('),(');
//> ["0,10", "1,15", "2,48", "3,63", "4,25", "5,95", "6,41", "7,31", "8,5", "15,2"]
var arr = my_str.split("),(")
arr[0] = arr[0].slice(2);
arr[arr.length-1] = arr[arr.length-1].slice(0,-2)
I have a javascript object that contains a property with values of another json stringified object. I cannot get the printout version of the string back to object form. See the following code. the console.log output content of json string is exactly as right side of jsonFromStr. However, JSON.parse(json) is OK, while JSON.parse(jsonFromStr) is error. What is wrong here?
jsfiddle: http://jsfiddle.net/jma7889/qtmmpj2t/
level2Obj = { key2a: "foo", key2b: 3};
level2ObjJson = JSON.stringify(level2Obj);
level1Obj = {key1a: "bar", key1b: {level2ObjJson}};
json = JSON.stringify(level1Obj);
jsonFromStr = '{"key1a":"bar","key1b":{"level2ObjJson":"{\"key2a\":\"foo\",\"key2b\":3}"}}'; // same than json
objFromStrify = JSON.parse(json); // OK
objFromAssignedString = JSON.parse(jsonFromStr); // Uncaught SyntaxError: Unexpected token l in JSON at position 45
If you do this it will work:
jsonFromStr = '{"key1a":"bar","key1b":{"level2ObjJson":"{\\\"key2a\\\":\\\"foo\\\",\\\"key2b\\\":3}"}}';
The reason that your version does not work is that the escape sequence \" is resolved at that very moment, and so the actual value of jsonFromStr will be:
'{"key1a":"bar","key1b":{"level2ObjJson":"{"key2a":"foo","key2b":3}"}}'
... which is invalid JSON.
You need to keep those escapes unresolved in the JSON string, and this you do by escaping the escape sequence itself with additional slashes.
jsonFromStr = '{"key1a":"bar","key1b":{"level2ObjJson":{\"key2a\":\"foo\",\"key2b\":3}}}';
You have an extra "" for value of level2ObjJson key,replace jsonFromStr in your code with the above code .
I have the following line of code:
data = jQuery.parseJSON(data);
Which is creating the following error...
SyntaxError: JSON Parse error: Unexpected EOF
I can't work out how to identify what's causing the error though.
Any ideas?
Here's the data...
{
"element_type": "paint",
"edit_element_id": "2117",
"paint_id": "15",
"paint_editable_data": "zwibbler3.[{\"id\":0,\"type\":\"GroupNode\",\"fillStyle\":\"#cccccc\",\"strokeStyle\":\"#000000\",\"lineWidth\":2,\"shadow\":false,\"matrix\":[1,0,0,1,0,0],\"layer\":\"default\"},{\"id\":1,\"type\":\"PageNode\",\"parent\":0,\"fillStyle\":\"#cccccc\",\"strokeStyle\":\"#000000\",\"lineWidth\":2,\"shadow\":false,\"matrix\":[1,0,0,1,0,0],\"layer\":\"default\"},{\"id\":2,\"type\":\"BrushNode\",\"parent\":1,\"fillStyle\":\"#cccccc\",\"strokeStyle\":\"#000000\",\"lineWidth\":10,\"shadow\":false,\"matrix\":[1,0,0,1,0,0],\"layer\":\"default\",\"points\":[17,21,17,22,17,24,17,28,18,34,37,55,49,59,70,61,89,56,92,55,93,54]},{\"id\":3,\"type\":\"PathNode\",\"parent\":1,\"fillStyle\":\"#e0e0e0\",\"strokeStyle\":\"#000000\",\"lineWidth\":2,\"shadow\":false,\"matrix\":[1,0,0,1,-14,-85],\"layer\":\"default\",\"textFillStyle\":\"#000000\",\"fontName\":\"Arial\",\"fontSize\":20,\"dashes\":\"\",\"smoothness\":0.3,\"sloppiness\":0,\"closed\":true,\"arrowSize\":0,\"arrowStyle\":\"simple\",\"doubleArrow\":false,\"text\":\"\",\"roundRadius\":0,\"commands\":[0,150,100,6,200,150,200,100,6,150,200,200,200,6,100,150,100,200,6,150,100,100,100,7],\"seed\":36934}]",
"paint_image_data": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALwAAAB1CAYAAAD0rovXAAASHklEQVR4Ae1dCXBW1RW+BAKJNAwihMWgkYkN+1JgRGAEBKQtISIVcBoQRGiKhBadQXQ07XQoVhwQtLiwVGSzUEAgwGgAIVgMyCbLsAlllzVSFSmLhPT7Hv/LvCwk77285V/Omfly33Lfued+9+T+d3v3KSUiDAgDwoAwIAwIA8KAMCAMCAPCgDAgDAgDwoAwIAwIA8KAMCAMCAPCgDAgDAgDwoAwIAwIA8KAMCAMCAPCgDAgDAgDwkA4M1ApnDMneSuTgXtwt34A9QzH+jU9pJKzpeBcsWvfMmKwizh8sJeQc/YlQ1VXoFsgrIvQSTkPZTkBbEB4CAg6sevwlZGTj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fP1SSSOSM0FMgE23VwXcXjXKXY9gWZIgY7/BFOKiYlRqampavDgwapFixa85Lvs3btXzZs3T2VlZenbaNAmvqFER9/HE69EHN4rpt1PpzWSeBXoB2jlmpSUpHr16qWhZcuW7ltgSIHLAbhEgjB8SY9Di5xj+CtgeeGXQb3tQ3F429QF7YPc/2YE8AxQR7eS7fsOHTpoE1gMGzXS+r367QqHHD/fsmWLys3N1UI2XwzCV/A48jITOGK47vmhOLznlHuWYDRSegTgMlriPqBQ2Obn4rT4+HgtLH6sn/OBCxcuKG5jp8N4rh8HFnYV6sfBSWBFAJ8j5AZJvos4vO9F4JkBXJDTFegWCJ1einkeenMC2IAwKDfEF4dHyUSo3IN81w+gnuFYv6aHpOdsKThX7BrfQBIRBoSBYGLg/9jYtJnVySp3AAAAAElFTkSuQmCC"
}
Is it the size that's the problem maybe?
It looks like you are trying to convert a text string into a JSON data object.
You should probably be doing the following:
instead of using jQuery.parseJSON(data), rather just use JSON.parse(data).
The error you mentioned indicates you are passing in an empty string "" as your value of data. So check the value that is being passed in to the parse method.
The data object you mentioned that you are passing in will always result in an error since it's already in a JSON format.
The parse method is intended to do the following conversion.
JSON.parse("{\"hello\":\"world\"}") returns {hello:'world'}
If you are trying to convert in an object into a string, you can try this:
JSON.stringify({hello:'world'}) returns "{\"hello\":\"world\"}"
The reason is simple. When you define the JSON in the script, the double quotes should be represented by \" , not " .
In my case i was also facing that same error in React-native but after look into my code i found that .. .my API hit URL was not complete .. and after that.. my problem was resolved :)
Maybe you can do with the eval method :
if (data !== null) {
var json_obj= eval("("+data+")"); //jQuery.parseJSON(data);
//just for check the the keys
var keys = Object.keys(json_obj);
for (var i = 0; i < keys.length; i++) {
console.log(keys[i]);
};
}
I have a string:
a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}"
I want to convert this a to a json data.
How to do it?
I have tried JSON.parse(), but it will raise an error.
SyntaxError: Unexpected token u
That looks like Python literal syntax to me. Tell whoever wrote the Python portion to encode as JSON instead of just outputting the structure as a string.
In this particular case, you can just replace each u'x' with "x" and you'll have valid JSON:
var a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}";
// Convert to JSON (May not work with other inputs!)
var json = a.replace(/u'((?:[^'\\]|\\.)*)'/g, function(a,str){
return '"' + str.replace(/\\'/g, '\'').replace(/"/g, '\\"') + '"';
});
// Parse the JSON into a Javascript object
var obj = JSON.parse(json);
Updated to work with some quotes in the object:
var a = "{u'a':[u'\\'123\\'',u'321'], u'b':[u'456\\\\',u'\"654\"']}";
Becomes:
{a:["'123'","321"], b:["456\",""654""]}
You need to change your input string to a valid JSON string.
I think this is what you wanted:
JSON.parse('{"a":["123","321"], "b":["456","654"]}')
The variables (keys / values ) are strings so need to be in quotes in order to be parsed as valid JSON.
// put quotes around the key / value pairs.
var a = "{\"u'a'\":[\"u'123'\",\"u'321'\"], \"u'b'\":[\"u'456'\",\"u'654'\"]}";
jQuery
a = $.parseJSON(a);
JSON is supposed to contain only strings.
a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}"
Here I can only assume that u is a variable. Change it to this:
a = "{"+u+"'a':["+u+"'123',"+u+"'321'], "+u+"'b':["+u+"'456',"+u+"'654']}"
I am encoding some model data into a html element like this:
#Html.Raw(Json.Encode(Model));
The json string returned looks like this:
{"TestList":[{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6144","SeqNo":9306,"SeqNoSpecified":true,"TSeqNo":8314,"TSeqNoSpecified":true,"TestDescr":"HBsAg"},{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6124","SeqNo":9295,"SeqNoSpecified":true,"TSeqNo":8315,"TSeqNoSpecified":true,"TestDescr":"HCV Ab"},{"FrequencyType":"1X","GCDs":"585.3","Identifier":"6","SeqNo":9729,"SeqNoSpecified":true,"TSeqNo":8309,"TSeqNoSpecified":true,"TestDescr":"HD Monthly LS"}],"Frequency":[{"Key":"ANNUAL","Value":"Annually"},{"Key":"BIMONTH","Value":"Bi-Monthly"},{"Key":"BIWEEK","Value":"Bi-Weekly"},{"Key":"MON","Value":"Monthly"},{"Key":"1X","Value":"One Time"},{"Key":"QTR","Value":"Quarterly"},{"Key":"SMAN","Value":"Semi-Annual"},{"Key":"WEEK","Value":"Weekly"}]};
When I try to parse this using JSON.parse, I get an error:
arrayTestList = [];
var jsonTestList = $('#TestList').text();
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]); // <===== this line is failing
Unable to get value of the property '0': object is null or undefined
How do I convert this jsonTestList string into a javascript array so that I can access elements of arrayTestList properly?
Edit:
Sorry, I forgot to mention my edit. Basically above javascript code is inside a Partial View 2. The code where I am json encoding the model is in another Partial View 1. From P V 2, I cannot access the model object of P V 1, so I am just dumping the contents into a div tag, so that I can access this list TestList element.
Try removing this line:
jsonTestList = JSON.stringify(jsonTestList);
jsonTestList is already a JSON string
The issue is now resolved.
I was getting an invalid character, but couldn't immediately recognize which character it was that was causing the problem. I found that my JSON string isn't valid because of the trailing semicolon that was output by the Json.Encode method. I validated the JSON string # http://jsonlint.com.
Once I removed that semicolon, the json string is populated as a JavaScript array into arrayTestList object.
Now just this works, as mentioned in both the answers above, JSON.stringify is not needed.
var arrayTestList = [];
var jsonTestList = $('#TestList').text().replace(";","");
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]);
Why are you using Json.Encode? Also in your code, why are you writing redundant code first you are using JSON.stringify and the JSON.parse same object.
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
As per my understanding just Html.Raw will work
In JavaScript
var jsonObject = #Html.Raw(Model.TestList); //Here you will get JavaScript Object
var jsonTestList = jsonObject.TestList;