I'm trying to get the JSON object from a JSON outputted string from a Rails app. Currently in JavaScript I'm doing:
data = "<%= #chromosomes.html_safe %>";
However, since there are quotes at the beginning and end of the JSON object, it is not being rendered as a JSON object. Instead it is doing something like
data = "[{"name":"YHet","organism_id":"4ea9b90e859723d3f7000037"}]"
Is there a way that I can remove the beginning and end quotes so that the object is treated as an array instead of a string?
Why don't you do:
data = <%= #chromosomes.html_safe %>;
Sidenote:
I hope you do something like:
#chromosomes = [{ name: "YHet", organism_id: "foo" }].to_json
If you are using jQuery you can do the following
var data = jQuery.parseJSON('[{"name":"YHet","organism_id":"4ea9b90e859723d3f7000037"}]');
Use JSON object that is included in most of browsers or if you are using jQuery use $.jsonParse method that try to use JSON object if defined otherwise parse using eval or some safer way.
On controller
#my_var = MyObj.find_by_id(4).to_json
On page in haml way.
var my_json = $.parseJSON("#{j #my_var}"); //used JQuery to parser JSON string
Use eval:
var dataObject = eval('(' + dataString + ')');
Related
I am trying to parse a simple JSON string using jQuery
var parsedJSON = $.parseJSON('{"graph_data": "{}"}');
I would expect typeof(parsedJSON.graph_data) to be an Object but instead it is returning string. What is the correct way to return an Object?
It should be like
var parsedJSON = $.parseJSON('{"graph_data": {}}');
console.log(typeof(parsedJSON.graph_data));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
no need of " for object, " is needed for defining string and object key. So it will treat as string here. For more about JSON structure and example visit http://www.json.org/.
try it.
var parsedJSON = $.parseJSON('{"graph_data": "{}"}');
console.log(parsedJSON.graph_data);
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;
Here is the JSON returned from my Server.
"[{"description":"A user","name":"test","type":"user"}]"
I want to remove the outer double quates. Which means I want the JSON as
[{"description":"A user","name":"test","type":"user"}]
How can I do this? Please help.
You want to turn the JSON into JS objects right? If so, you would do JSON.parse(json). If you need IE7 support, you have to include a polyfill for JSON as it's not supported in IE7<.
You can get the current JSON polyfill here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
As the response from the server is not valid JSON you have to request it as text, fix it, and parse it as JSON. Use dataType: 'text' in your options in the ajax call.
Use the substr method to cut of the first and last character:
data = data.substr(1, data.length - 2);
Then you can parse the JSON:
var obj = $.parseJSON(data);
To strip the first and last character from a string:
var fixed_string = string.substring(1, string.length - 1);
var str = '[{"description":"A user","name":"test","type":"user"}]';
var data = (new Function( "return " +s))();
console.log(f);
In your case response from server is a json string you have to convert it to json object
var str = '[{"description":"A user","name":"test","type":"user"}]';
str = eval('('+str+')');
console.log(str[0].name) //this will give test
Hope this helps.
This code works:
$(this).load($('.pageloadlabel', this).attr('href'), {category: 1});
This code doesn't work:
var data = '{category: 1}';
$(this).load($('.pageloadlabel', this).attr('href'), data);
The question is, how can I make it work?
Your data is not a Javascript object but a string, you can convert it to object by eval e.g.
data = eval('(' + data + ')');
but eval is considered dangerous, so better to parse string as JSON e.g.
data = JSON.parse(data)
For JSON lib you can use json2
It's not JSON, it's a javascript object.
var data = { category: 1 };
If you have a string, you would have to convert it to a object.
And notice that your string is not a valid JSON, see the link for more details.
Take out the quotes, the load function is expecting an object, not a string.
Have you tried to use eval() on data?
var data = '{category: 1}';
$(this).load($('.pageloadlabel', this).attr('href'), eval(data));