I have a JSON array and I need to use the data in my application. I am calling it through javascript and I can iterate between the variables.
The problem I have, is the data isn't usable because of the '+' characters and the %2C etc.
"events":[{"url":"","name":"Test+Event2","location":"Some+little+village","eventDate":"Wednesday%2C+20th+August+2014+from+10%3A00+to+11%3A00"}
Is there a Javascript or JQuery solution to filter the strings?
It looks like it is a URL Encoded JSON string. var json_string = decodeURIComponent(uri_encoded_string) should do the job.
Related
I've a string in JSON format. I'm trying to iterate it. I have validate the string whether its JSON or not. It is fine. But, when I try to iterate it, it throws me error .
Here is my
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":"{\"color\": \"blue\",\"value\": \"#f00\"}"},{"id":8,"userId":"123","courseId":"C5","courseValue":"{\"color\": \"green\",\"value\": \"#f00\"}"}]';
Here is the fiddle
http://jsfiddle.net/hLkUz/40/
You have taken some JSON and wrapped ' around it to try to make it a JavaScript string literal.
Some characters have special meaning in JavaScript string literals (such as \ which starts an escape sequence). You have failed to escape them within the string.
Consequently, to take an example:
"{\"color\":…
… when parsed as part of the JavaScript string literal becomes:
"{"color":…
… which isn't valid JSON.
You need to escape the special characters for the JavaScript string literal.
Better yet, restructure your JSON so that it doesn't contain values which are encoded as JSON themselves. Use an object instead of a string containing JSON representing an object.
You are having unwanted double string in values. Corrected json string is here
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":{\"color\": \"blue\",\"value\": \"#f00\"}},{"id":8,"userId":"123","courseId":"C5","courseValue":{\"color\": \"green\",\"value\": \"#f00\"}}]';
Try this:
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":{"color": "blue","value": "#f00"}},{"id":8,"userId":"123","courseId":"C5","courseValue":{"color": "green","value": "#f00"}}]';
There's no need to wrap the object with " nor escape it.
What you need is this:
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":{"color": "blue","value": "#f00"}},{"id":8,"userId":"123","courseId":"C5","courseValue":{"color": "green","value": "#f00"}}]';
Fiddle
I'm not sure if you intend to escape the JSON within courseValue. However it seems like the escaping of the nested objects is the problem. This works
http://jsbin.com/mekiwalidu/edit?js,console,output
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":{"color": "blue","value": "#f00"}},{"id":8,"userId":"123","courseId":"C5","courseValue":{"color": "green","value": "#f00"}}]';
var obj = JSON.parse(string);
console.log(obj);
I have json on my page coming from the string property of the model:
var myJson = '[{\"A\":1,\"B\":10,\"C\":\"214.53599548339844\",\"D\":\"72.52798461914062\"},
{\"A\":1,\"B\":11,\"C\":\"214.53599548339844\",\"D\":\"72.52798461914062\"}]'
I want to process that json via javascript on the page
I am doing $.parseJSON(#Html.Raw(Json.Encode(myJason))); but json still contain \" symbol. If i do $.parseJSON(#Html.Raw(Json.Decode(myJason))); it is just producing an $.parseJSON(System.Web.Helpers.DynamicJsonArray); How can I fix that?
Take your JSON and .stringify() it. Then use the .replace() method and replace all occurrences of ("\").
var myString = JSON.stringify(myJson);
var myNewString = myString.replace(/\\/g, "");
Hope this helps.
There are two ways
1 from where you get the JSON asked them to send you as url encoded format. at your end you need to decode url and you will get the Perfect JSON.
Other wise do the laborious replace method for each and every special charecter with respective char.
like above example you need to use replace("\","");
There is no JSON parser that will be able to deal with a JSON string that isn't properly formatted in the first place.
so you need to make sure that your theModel is formatted appropriately and according JSON.org standards.
Like
Koushik say you can use String operation
Hello im working on a project were i have to update a database filled with JSON data. However this data looks like this:
{\"Id\":\"1\",\"Sounding\":\"1.075\",\"Ullage\":\"0\",\"Full\":\"100\",\"CapacityM\":\"3.918\",\"CapacityMT\":\"3.918\",\"LCG\":\"3.779\",\"TCG\":\"0\",\"VCG\":\"2.39\",\"FSM\":\"4.492\"}
However if i convert the original data to json format (from CSV file), it appears like this:
{"ID":1,"SOUNDING":1.075,"ULLAGE":0.000,"FULL":100.000,"CAPACITY":3.918,"CAPACITY":3.918,"LCG":3.779,"TCG":0.000,"VCG":2.390,"FSM
":0.000}
How do i add all those slashes like in the first one so it is the correct format? Do I really need them?
Looks like the string in database is javascript (or C- or Java-, you should check) string escaped. Simplest way to do that is use org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript() or org.apache.commons.lang.StringEscapeUtils.escapeJavaScript() method. Also check the other methods of these classes.
Alternative would be to store the first JSON as string in 2nd temp JSON object, then convert the 2nd JSON object to string, then get substring containing just the escaped string value of 1st JSON object out of that (I think that would be the part between the 3rd and last double quotes in the 2nd JSON string...). Slightly hacky, but avoids adding extra library.
That looks like the data has been escaped for some programming language's string/text literal format.
If I have not misunderstood anything I think you can solve this using json_parse.
Here is an example: http://jsfiddle.net/mqchen/yEJdq/
json_parse(data, function(key, value) {
var floatVal = parseFloat(value);
return !isNaN(floatVal) && isFinite(value) ? floatVal : value;
});
It uses json_parse but sends it a delegate which interprets strings that look like numbers as numbers.
EDIT: here is a version which also converts all keys to uppercase (in case you also want that): http://jsfiddle.net/mqchen/yEJdq/2/
I am using Dojo.fromJson to convert json string to javascript object, but throw exception. Because, there are control characters such as ',\n,\r in the json string.
How can I solve this problem in dojo? convert json string to javascript object, even if there are control characters.
I use Newtonsoft.JsonConvert.SerializeObject to convert C# oject to json data. Json Object: {"name":"'\"abc\n123\r"} then, I use Dojo.fromJson(' {"name":"'\"abc\n123\r"}') to convert json data to javascript object.
Thank you very much!
Problem, i believe is the double-quote which should be escaped by triple backslashes. You can use "native browser JSON decode" as searchterm for "dojo fromJson" synonym.
Without knowing my way around C# - I havent tested but i believe following should work:
string c_sharp_name = "'\"abc\n123\r";
// C#Object.name
c_sharp_name = c_sharp_name.
replace('"', '\\"'). // maybe add a slash on serverside
replace('\n', '\\\n').
replace('\r', '\\\r');
since
while this fails:
{"name":"'\"abc\n123\r"} // your single backslash
this would work:
{"name":"'\\\"abc\\\n123\\\r"} // working triple backslash escape
Since the JSON format specifies that single quotes should not be escaped, most libraries (or even the native JSON parser) will fail if you have an escaped single quote in it. Now this usually is not a problem since most of the time you do an XHR that fetches some data formatted as JSON and you use the responseText which contains your JSON string that you can then parse, etc.
In this particular situation, I have a JSON string stored in a database as text... so the database contains something like {"property":"value"} and I want to output this as part of an HTML page created by the server so that the JavaScript code in that page looks something like this:
var x = '{"property":"value"}';
Now if the JSON string in the database contains a single quote like this:
{"property":"val'ue"}
Then I need to escape it or else I will never be able to use it as a string:
console.clear();
var obj = {prop:"val'ue"};
var str = JSON.stringify(obj);
console.log("JSON string is %s",str);
console.dir(JSON.parse(str)); //No problem here
//This obviously can't work since the string is closed and it causes an invalid script
//console.dir(JSON.parse('{prop:"val'ue"}'));
//so I need to escape it to use a literal JSON string
console.dir(JSON.parse('{"prop":"val\'ue"}'));
The question then is why {"prop":"val\'ue"} not considered a valid JSON string ?
In JavaScript - the string '{"prop":"val\'ue"}' is a correct way to encode the JSON as a string literal.
As the JavaScript interpreter reads the single-quoted string, it will convert the \' to '. The value of the string is {"prop":"val'ue"} which is valid JSON.
In order to create the invalid JSON string, you would have to write '{"prop":"val\\\'ue"}'
If I understand the question right, you are trying to generate JavaScript code that will set some variable to the decoded version of a JSON string you have stored in the database. So now you are encoding the string again, as the way to get this string into JavaScript is to use a string literal, passing it through JSON.parse(). You can probably rely on using the server side JSON encoder to encode the JSON string as a JavaScript string literal. For instance:
<?php $jsonString = '{"prop":"val\'ue"}'; ?>
var myJson = JSON.parse(<?php echo json_encode($jsonString) ?>);
// Prints out:
// var myJson = JSON.parse("{\"prop\":\"val'ue\"}");
// And results: Object - { prop: "val'ue"}
However, If you are 100% sure the JSON is going to be valid, and don't need the weight of the extra parsing / error checking - you could skip all that extra encoding and just write:
var myJson = <?php echo $jsonString; ?>
Remember, JSON is valid JavaScript syntax for defining objects after all!
According to jsonlint it is valid without escaping the single quote, so this is fine:
{"prop": "val'ue"}
But this is invalid:
{"prop":"val\'ue"}
According to json.org json:
is completely language independent but
uses conventions that are familiar to
programmers of the C-family of
languages, including C, C++, C#, Java,
JavaScript, Perl, Python, and many
others
So it is the language conventions in c-type languages regarding the reverse solidus (\) that means that your example is not valid.
You might try the following, however, it's ugly.
JSON.parse("{\"obj\":\"val'ue\"}");
Or just store the string to a var first. This should not store the literal backslash value and therefore the JSON parser should work.
var str = '{"obj" : "val\'ue"}';
JSON.parse(str);