How can i parse some object that stringify twice?
Most of the time in my code it is not problem but some times it stringify twice, and I can not trace the code to find my problem.
My JSON object something like this:
""[{\"name\":\"trane\",\"price\":\"150000\",\"order\":\"\",\"sale\":\"\",\"printedPic\":\"\",\"remainingPic\":\"\",\"locationEncome\":\"\"}]""
It's definitely best to figure out where and why it's stringifying twice, but you can just parse twice if you have to.
JSON.parse(JSON.parse("JSON STRING HERE"))
Edit
Potentially you're stringifying an already stringified object, this could help you figure out what is going wrong.
Add this function to your code and then replace your JSON.stringify calls to JSON.stringifyIfObject calls. Just use this as a means of debugging though, I wouldn't put this into production.
JSON.stringifyIfObject = function stringifyIfObject(obj){
if(typeof obj == "object")
return JSON.stringify(obj);
else{
alert("found already stringified object")
return obj;
}
}
This post is a little bit old but I had the same problem today and it was caused by a third party library.
Javascript library Prototype.js applies JSON.stringify() twice when it is used in version 1.6.x (it seems that this bug was removed in version 1.7)
The following code :
var test = ["banana"];
JSON.stringify(test);
will give you the following result :
""[\"banana\"]""
instead of (normally expected) :
"["banana"]"
Here is my source :
https://github.com/krinkle/jquery-json/issues/35
If that happens to you, the best option is to upgrade that library if you can.
Related
In my angularjs apps, I usually parse a JSON string by using angular.fromJson, like so:
var myObject=angular.fromJSON(jsonString);
However, it seems that I would obtain the same result by using $scope.$eval:
var myObject=$scope.$eval(jsonString);
See this fiddle
Or by using vanilla javaScript, like so:
var myObject=JSON.parse(jsonString);
Is there any particular reason to use angular.fromJSON rather than JSON.parse?
Is there any possible issue when using $scope.$eval to parse a JSON string?
Check out the source code:
function fromJson(json) {
return isString(json)
? JSON.parse(json)
: json;
}
They're just passing through to JSON.parse.
As for $eval it shells out to $parse:
// $scope.$eval source:
$eval: function(expr, locals) {
return $parse(expr)(this, locals);
},
$parse source is too long to post, but it is essentially capable of converting inline (stringified) objects to real Objects and so it makes sense that in this case, it will actually convert your JSON as well.
(I did not know this until reading through the $parse source just now.)
Is there any particular reason to use angular.fromJSON rather than JSON.parse?
Nope, not really. Although they do check to you to ensure that you don't double-parse a JSON string, like so:
var jsonString = '{"foo":"bar"}';
var json = JSON.parse(jsonString); // Parsing once is good :)
JSON.parse(json); // Parsing twice is bad :(
Is there any possible issue when using $scope.$eval to parse a JSON string?
I don't think so off the top of my head, other than that you're doing more work than is necessary. So if you know you have JSON, there's no reason to use the heavier $parse function.
The above answer is almost correct. However, there is a potential issue with using $scope.$eval() to parse a JSON string, which does not exist with either JSON.parse() or angular.fromJson(): security. Angular allows an expression to contain complex JavaScript including function calls, conditionals with ?:, variable assignments, and so on. All of these are recognised and processed if you use $scope.$eval(), even if they were added by a malicious end-user.
JSON does not support any of those more complex JavaScript features, nor anything else potentially "dangerous". If you use a true JSON parser like JSON.parse() or angular.fromJson(), there is no chance of malicious code being injected and executed.
Since Angular expressions are isolated and evaluate only in the current $scope, the risk of code injection is somewhat mitigated - $scope.$eval() is far less dangerous than JavaScript's native eval() for parsing JSON. However there is still no reason to use either function for this purpose, since there is a potential security risk and using a proper JSON parser is likely to be faster.
I am using jquery CSV library (https://github.com/evanplaice/jquery-csv/) , to parse and convert a CSV file into an array of objects. This is my code
this.parsedData = $.csv.toObjects(data);
if (this.parsedData.length === 0) {
**console.log('In valid'); /**/ This gets printed
} else {
console.log('valid')
}
My CSV file is this:
""__stream_code","project_code","process","due_date","root_table"
"DASH_PLAY_001","DEV","Plate",2013-02-02,"stream"
"DASH_PLAY_001","DEV","DepthAssess",2013-02-03,"stream""
Now, if I remove quotes, it works fine, but with quotes it doesn't.
Most of the time, my application is going to handle CSV with values in quotes.
Is there any way to fix it?
Try with http://papaparse.com/; you can parse it online and it works great.
All you have to do is call through var results = $.parse(csvString);
and it will return the JSON object for you.
Why is it wrapped in quotes?
I've tested it without the outer quotes on the Basic Usage demo and it seems to parse the data just fine. Are you using at least version 0.71?
This:
""__stream_code","project_code","process","due_date","root_table"
"DASH_PLAY_001","DEV","Plate",2013-02-02,"stream"
"DASH_PLAY_001","DEV","DepthAssess",2013-02-03,"stream""
Double-double quotes cancel each out (as per the spec) so this'll error when it tries to parse the first value.
Should be:
"__stream_code","project_code","process","due_date","root_table"
"DASH_PLAY_001","DEV","Plate",2013-02-02,"stream"
"DASH_PLAY_001","DEV","DepthAssess",2013-02-03,"stream"
If jquery-csv encounters an error during parsing it should log an error to the console indicating the row:column where the error occurred. Is there an error in the console. If not what does console.log(data) output?
As for the data being a mix of quoted/unquoted, the parser shouldn't have any issues consuming it. The data (sans outer quotes) looks perfectly valid.
BTW, I'm not trying to shed blame. If there is something else here that isn't in the code sample you provided that exposes a bug in the parser, I'd like to identify and fix it.
Disclaimer: I'm the author of jquery-csv
This is the first time Im asking a question on Stackoverflow, so i excuse in advance if its not properly formulated
I'll keep it it short and simple. I want to convert what i get from this url:
http://hotell.difi.no/api/json/brreg/enhetsregisteret?query=company
to a JSON or array in JavaScript, how do i do this?.
This is going to be a part of a search-webapplication where I just change the query parameter when the user changes the input.
I must admit that I'm completely new at this, and I don't even know if I'm asking the question correctly.
If you want to make a string into a json object, simply use JSON.parse():
var obj = JSON.parse(string);
You can use jQuery.getJSON() if you are using Ajax and you don't mind jQuery:
var obj = $.getJSON( "http://hotell.difi.no/api/json/brreg/enhetsregisteret?query=company", function() {
console.log( "DONE" );
})
Keyword "urlparse javascript"
Node server
url.parse()
Client
This (creating an <a> DOM object) is quick and dirty, but it works:
https://gist.github.com/jlong/2428561
Do use more stable library such as parseuri and URI.js for this task.
I am running
var n = [];
jQuery.toJSON( n );
On one page I get "[]" on the other ""[]"". On both pages I run the same jQuery version with a toJson Plugin.
In Firefox DOM I can see both arrays have the same function names, but ... different:
all b(B, A)
any j(B, A)
all all(iterator, context)
any any(iterator, context)
I guess there are some Array.prototype functions before my script. That causing the arrays to be different. I can't change the other code I have to somehow deal with this.
I tried new Array() and jQuery.makeArray(n), still same result. I actually don't care that the arrays are not equal but how do I get the same JSON code for this? It's getting worse if I have strings in the array: ""[\"a\", \"b\"]""
The extra quotes are caused by the
Array.prototype.toJSON
function that is defined by the Prototype library and possibly other libraries as well. This function is called by jQuery.toJSON (or JSON.Stringify() for that matter) and produces the extra quotes. If you would use
delete Array.prototype.toJSON // remove toJSON for all Arrays
//or
delete n.toJSON // remove toJSON for specific Array
before you do the jQuery.toJSON, that should work!
As another suggestion, it is better to use
JSON.stringify(object)
instead of jQuery.toJSON. It is supported natively in most browsers. If you want to be sure it works everywhere, use https://github.com/douglascrockford/JSON-js, it is the basis used for the JSON.stringify() function.
For JSON.stringify(), see https://developer.mozilla.org/En/Using_native_JSON for more info.
My dirty hack for this is:
function cleanJson(s)
{
if (s[0] == '"')
{
s = s.substring(1, s.length-1).replace(/\\"/g,'"');
}
return s;
}
Does the job, but I am still looking for a cleaner solution.
I'm trying to develop a web application using jQuery, AJAX and JSON.
I have this code:
console.log(response.s);
if (response.s == true) {
alert('good');
} else {
alert('bad');
}
This response (via console.log() on Firebug) seems to be:
{"s":true}
Which seems to be a JSON object right?
Well, the line console.log(response.s); on the first code I added here returns undefined. What's the problem?
What is typeof (response)? if it's a string then you have to parse it, first. (You'd be accessing the s field of a string, which doesn't exist, so JavaScript gives you undefined instead of throwing an Exception or whatever.)
If the content-type of the response isn't application/json then the javascript is probably assuming that it is just a string.
Supplying the correct content header should therefore sort your problem.
Alternatively you could probably use eval() to convert the string into a json object.
try to use:
var obj = jQuery.parseJSON(response);
console.log(obj.s);
Hope it helps.