JavaScript - Parsing JSON with carriage and new line spaces - javascript

I am using the following JS code to parse a JSON string from a separate JS file:
// extract JSON from a module's JS
var jsonMatch = data.match( /\/\*JSON\[\*\/([\s\S]*?)\/\*\]JSON\*\// );
data = JSON.parse( jsonMatch ? jsonMatch[1] : data );
This is an example of the JS file I extract the JSON string from:
JsonString = /*JSON[*/{"entities":[{"type":"EntityPlayer","x":88,"y":138}]}/*]JSON*/;
This code works just fine, however if the JS file with the JSON string contains carriage returns and isn't on one complete line then I get a syntax error.
Example:
JsonString = /*JSON[*/{
"entities":[{
"type":"EntityPlayer",
"x":88,
"y":138}]
}/*]JSON*/;
Returns the following error:
JSON.parse: unexpected non-whitespace character after JSON data
Any idea how I could modify my parsing to work by either stripping out whitespace or to remove carriage returns and new line spaces?

data = JSON.parse( (jsonMatch ? jsonMatch[1] : data).replace(/\n/g,"") );

Did not test it, but maybe this is what you are looking for?
var JsonString = JsonString.replace(new RegExp( "\\n", "g" ),"");
(from http://www.bennadel.com/blog/161-Ask-Ben-Javascript-Replace-And-Multiple-Lines-Line-Breaks.htm)

Related

Parse Complex Json String

I'm attempting to parse the following JSON string (not in control of the format, I know it's hideous).
var json = '{"what.1.does":"anything", "nestedjsonstr":"{\"whatup\":\"nada\"}"}';
obj = JSON.parse(json);
I'm getting Error: Unexpected token w in JSON at position 43 which is where the first value of nestedjsonstr begins. Is there any elegant way to parse this?
Maybe this can help you out. You replace the curly braces inside your string without the ", and remove the \.
var json = '{"what.1.does":"anything", "nestedjsonstr":"{\"whatup\":\"nada\"}"}';
json = json.replace('\"{', '{').replace('}\"', '}').replace('\\"', '"');
obj = JSON.parse(json);
console.log(obj);

Serialize for JavaScript apex

I need to serialize some simple object from .NET to JavaScript...
But I've some problem with apex...
C# example
var obj = new { id = 0, label = #"some ""important"" text" };
string json1 = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(obj,
new Newtonsoft.Json.JsonSerializerSettings()
{
StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml
});
JavaScript example
var resJson1= JSON.parse('{"id":0,"label":"some \"important\" text"}');
var resJson2= JSON.parse('{"id":0,"label":"some \u0022important\u0022 text"}');
Both parse give me the same error
VM517:1 Uncaught SyntaxError: Unexpected token I in JSON at position
23 at JSON.parse(<anonymous>)
Where am I wrong?
You're pasting the generated string of JSON into a JavaScript string constant without escaping it further. Try
console.log('{"id":0,"label":"some \"important\" text"}');
You'll see {"id":0,"label":"some "important" text"} i.e. the "important" quotes are no longer escaped by backslashes. (And you'll get the same for your \u0022 example too.) If you want to paste in the backslashes you'll have to escape them again:
var resJson1= JSON.parse('{"id":0,"label":"some \\"important\\" text"}');
The JSON you've generated with a single backslash would be fine if read from a file or URL, just not pasted into JavaScript as a string constant.

Cast a string to JSON using JavaScript

I have a string that looks like this:
"{""c1"": ""value1"", ""c2"": ""value2""}"
As you can notice, it is in JSON format. I store it in an SQLITE database, and then I use the following Javascript code to get it again in JSON format :
var req= "SELECT json_column from my_table";
var result = execSQL(req);
for (var index in res) {
var row= res[index];
consoleLog("test getad ", JSON.parse(row["json_column "]));
But I get this error :
<JSContext: 0x1c0044aa0> SyntaxError: JSON Parse error: Expected '}'
Can you please tell me why I have this error, I've spent hours trying to resolve it but with no success. I can change the string format if it is necessary, all I need is to get it again from SQLITE as JSON object.
Thank you in advance.
That string of yours is not valid JSON, this one is, based on your string content.
'{"c1": "value1", "c2": "value2"}'
As you can see the key/value pair is surrounded with one double quote ", not two, and the whole string with single quotes '. If the whole string would use double quote, the inner one's would needed to be escaped, like this
"{\"c1\": \"value1\", \"c2\": \"value2\"}"
For further reading about JSON, this post has a lot
What is the correct JSON content type?
Here is a sample showing their output
// these gets properly printed
// correct formatted JSON
console.log( JSON.parse('{"c1": "value1", "c2": "value2"}') );
// correct formatted JSON, outer doulbe quotes and inner, escaped one's
console.log( JSON.parse("{\"c1\": \"value1\", \"c2\": \"value2\"}") );
// yours wrapped with single quotes and inner double quotes, changed to one
console.log( JSON.parse('{""c1"": ""value1"", ""c2"": ""value2""}'.replace(/""/g, '"')) );
// these generates script error
// yours wrapped with single quotes
console.log( JSON.parse('{""c1"": ""value1"", ""c2"": ""value2""}') );
// yours as is, and had to comment this out, as if not, it crashes itself and all the above
//console.log( JSON.parse("{""c1"": ""value1"", ""c2"": ""value2""}") );
Your string is not in the right format. That is why the JSON.parse() cannot read it.
Your string:
"{""c1"": ""value1"", ""c2"": ""value2""}"
Try making it like this:
'{"c1": "value1", "c2": "value2"}'

how to remove the whole script tag content from the fetched json data using JSON API?

Problems encountered when fetching data using JSON API:
The request method I used is: "http://www.example.org/?json=get_post&post_id=47. "
However the returned JSON file comes with a <script> block, which caused a problem :
<script>
document.cookie="kentopvc_22238=yes";
</script>
<script>
document.cookie="kentopvc_22238=yes";
</script>
{"status":"ok","post":{"id":22238,"type": ........... }
error information
If you don't have access to the API that's returning the malformed data, you'll need to capture the string with Regex and then parse it.
var jsonString = response.match(/^{.*$/m)[0]
var parsedJson = JSON.parse(jsonString)
regex explanation
/ // beginning of pattern
^ // starts at the beginning of a new line
{ // looks for a bracket immediately following a new line
.* // any subsequent characters
$ // until we reach the end of the line
/ // end of pattern
m // the 'multiline' flag, necessary for the use of ^
[0] // match() returns matches in an array. we want the first (and in this case only) match

Why does JS String differ from JSON String?

I'm using this lib to display emojis.
I want to get my data from a JSON, but for some reason the lib cannot convert a string from JSON.
When I create my own string with the same data, e.g. '\uD83D\uDE18' it displays without any problem.
emojis.posts[0].content == '\uD83D\uDE18' returned false
So my question is, what is the difference between a 'normal' string and a JSON string?
JSON
{
   "title": "l\\u2764 you\\uD83D\\uDE18"
}
...
var emojis = JSON.parse(jsonString);
console.log(emojis.title);
returns 'l\u2764 you\uD83D\uDE18'
Creating a JSON in JS
var emojis = JSON.parse('{"title": "l\\u2764 you\\uD83D\\uDE18"}');
console.log(emojis.title);
returns 'l❤ you😘'
Found the answer: https://stackoverflow.com/a/7885499/6216557
This is a unicode, escaped string. First the string was escaped, then
encoded with unicode

Categories