Why doesn't JSON.parse work? - javascript

Why doesn't JSON.parse behave as expected?
In this example, the alert doesn't fire:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Testing JSON.parse</title>
<script type="text/javascript" src="js/json2.js">
// json2.js can be found here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
</script>
<script type="text/javascript">
function testJSONParse()
{
var text = '[{"a":"w","b","x"},{"a":"y","b":"z"}]';
alert(JSON.parse(text));
}
window.onload = testJSONParse;
</script>
</head>
<body>
</body>
</html>
In firefox, the Error Console says "JSON.parse". Not very descriptive..
This is a simplification of a problem I have which uses AJAX to fetch data from a database and acquires the result as a JSON string (a string representing a JSON object) of the same form as text in the example above.

Your JSON is not formatted correctly:
var text = '[{"a":"w","b","x"},{"a":"y","b":"z"}]';
^-- This should be a ':'
It should be:
var text = '[{"a":"w","b":"x"},{"a":"y","b":"z"}]';

error in typing
var text = '[{"a":"w","b":"x"},{"a":"y","b":"z"}]';
//below is correct one
var text = '[{"a":"w","b":"x"},{"a":"y","b":"z"}]';
alert(JSON.parse(text));

Related

Error while parsing JSON string using JQuery

I am trying to read values from JSON string and display some of it's values using JavaScript alert() statement. But I am getting following exception in the console.
Please guide.
Console Exception
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
...dc=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(a){...
at jquery.min.js(line 4, col 5304)
process.js
$(document).ready(function () {
//for handling json data
var json = $("#studentJsonDiv").data("students-json");
console.log(json);
$.each($.parseJSON(json), function (idx, obj) {
alert(obj.name);
});
});
home.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/process.js"></script>
</head>
<body>
From JQuery (JSON): <div id="studentJsonDiv" data-students-json='${studentsJson}'></div>
</body>
</html>
View Page Source of home.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/process.js"></script>
</head>
<body>
From JQuery (JSON): <div id="studentJsonDiv" data-students-json='[{"id":1,"name":"Jack"},{"id":2,"name":"Jill"}]'></div>
</body>
</html>
Since jQuery 1.6 the .data() method parses the values, so remove the $.parseJSON(). You are parsing the object not string that causing the error here. Also check - Why is jQuery automatically parsing my data-* attributes?
Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). A value is only converted to a number if doing so doesn't change the value's representation. For example, "1E02" and "100.000" are equivalent as numbers (numeric value 100) but converting them would alter their representation so they are left as strings. The string value "100" is converted to the number 100.
When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string. ( Taken from https://api.jquery.com/data/ )
$(document).ready(function() {
//static message
var msg = "Hello World from JQuery!";
$("#mydiv").text(msg);
//dynamic message processing for displaying value in div element
var students = $("#studentDiv").data("students");
$("#studentDiv").text(students);
//for handling json data
var json = $("#studentJsonDiv").data("students-json");
// change value here ---------------^------^------
console.log(json);
$.each(json, function(idx, obj) {
alert(obj.name);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mydiv"></div>
From JQuery:
<div id="studentDiv" data-students="[Student{id=1, name=Jack}, Student{id=2, name=Jill}]"></div>
From JQuery (JSON):
<div id="studentJsonDiv" data-students-json='[{"id":1,"name":"Jack"},{"id":2,"name":"Jill"}]'></div>
The data you get is an Array of objects. You just have to iterate over it, without having to parse it again. Also, correct attribute name.
var json = $("#studentJsonDiv").data("students-json");
$.each(json, function (idx, obj) {
alert(obj.name);
});
You need to use students-json in data because that is where you have your json data
var json = $("#studentJsonDiv").data("students-json");
$.each($.parseJSON(json), function(idx, obj) {
alert(obj.name);
});
If you're parsing
[Student{id=1, name=Jack}, Student{id=2, name=Jill}]
it's missing : after Student.

Issue with getElementById

I have written the following code to display an input with Javascript's alert( ... ) function.
My aim is to take a URL as input and open it in a new window. I concatenate it with 'http://' and then execute window.open().
However, I just get 'http://' in the URL name, even after concatenation, and not the complete URL. How can I fix this?
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<body onload="onload();">
<input type="text" name="enter" value="" id="url_id">
<input type="button" value="Submit" onclick="func();">
</body>
<script type="text/javascript">
var url;
function onload() {
url = document.getElementById("url_id").value;
}
function func(){
var var1 = "http://";
var var2 = url;
var res = var1.concat(var2);
alert(var2);
//window.open(res);
}
</script>
</head>
</html>
You shouldn't be calling it in onload(), only after the user has entered the url into the input field. Of course its an empty string, because you assign url to the value of #url_id before the user has a chance to enter anything when you place it in onload().
function func(){
var var1 = "http://";
url = document.getElementById("url_id").value;
var var2 = url;
var res = var1.concat(var2);
alert(var2);
//window.open(res);
}
Others have given solutions, and you already have accepted one. But none of them have told you what is wrong with your code.
Fristly, you have a body element inside your head element. This is invalid markup. Please correct it:
<html>
<head>
<!-- this is a script -->
<script type="text/javascript">
// javascript code
</script>
</head>
<body>
<!-- this is an inline script -->
<script type="text/javascript">
// javascript code
</script>
</body>
</html>
Secondly, you need to have an idea about the execution order of JavaScript inside browser windows. Consider this example:
<html>
<body onload="alert('onload')">
<p>Lorem Ipsum</p>
<script type="text/javascript" >
alert('inline');
</script>
</body>
</html>
Which alert do you thing will get executed first? See the JSFiddle.
So as you can see, inline JavaScript will be executed first, and then the browser will call whatever code is in <body onload=.
Also, onload function is called immediately after the page is loaded. And user has not entered anything when the function is executed. That is why you get null for url.
function func()
var url = document.getElementById("url_id").value;
var fullUrl = "http://".concat(url);
alert(fullUrl);
// or window.open(fullUrl);
}
You're not concatenating with a String but with an Object. Specifically an HTMLInputElement object.
If you want the url from the text input, you need to concatenate with url.value.
if its not concatenating, use:
var res = val1+val2.value;

Concatenate Strings in JavaScript

I Have edited the code, the updated code is below, This code is not able to fetch the keywords meta tag, hence it is not working.
old description: I am trying to concatinate the strings to get the finalUrl, but I am not able to do so becuase of the tags variable. I need to fetch the keywords meta tag of the page and append it to get the finalUrl. Any help?
<script type="text/javascript">
var tags=$('meta[name=keywords]').attr("content");
var gameurl = "http://xyz/abc/details/";
var jsn = ".json?callback=showGameDetail";
var finalUrl= gameurl.concat(tags).concat(jsn);
function loadJSON(url) {
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = url;
headID.appendChild(newScript);
}
function showGameDetail(feed){
var title = feed.title;
var game_url = feed.pscomurl;
var packart_url = feed.Packart;
$("#bnr-ads-box").html("<img src='"+"http://abc.com/"+packart_url+"'>");
}
loadJSON(finalUrl);
</script>
<div id="bnr-ads-box"></div>
<!DOCTYPE html>
<html>
<head>
<meta id="metaK" name="keywords" content="customizable software for QuickBooks, QuickBooks-integrated, Method customization, CRM accounting, Method for QuickBooks, Method CRM, Method blog, Salesforce automation, Method online platform, QuickBooks customization, web-based platform, industry-specific, customer portal, Method Field Services, Method Manufacturing, ERP" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<p id="demo">Click the button to join two strings into one new string.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var tags=$('meta[name=keywords]').attr("content");
var gameurl = "http://xyz/abc/names/";
var jsn = ".json?callback=showGameDetail";
var finalUrl= gameurl.concat(tags).concat(jsn);
document.getElementById("demo").innerHTML=finalUrl;
}
</script>
</body>
</html>
change this
var tags="$('meta[name=keywords]').attr("content");";
to
var tags=$('meta[name=keywords]').attr("content");
also use this code var finalUrl = gameurl + tags + jsn;
What you need is to escape the double quotes inside your tags variable, like so:
var tags="$('meta[name=keywords]').attr(\"content\");";
Cris' solution is also fine, but in some case you will need to have two sets of double quotes inside a string so you will be forced to do escaping correctly.
FYI: Escaping is the process of having special characters getting generated in a string which would otherwise cause issues, for instance in javascript you can't have newlines in a string, like this:
var mystring = 'on
a different line'; // <- this causes a syntax error
So one would do the following:
var mystring = 'on\na different line';
You forgot to include the jquery
<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="hello"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function myFunction()
{
alert("Hello World!");
var tags=$('meta[name=keywords]').attr("content");
var gameurl = "http://xyz/abc/names/";
var jsn = ".json?callback=showGameDetail";
var finalUrl= gameurl.concat(tags).concat(jsn);
alert(finalUrl);
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
Tough debatable, you can use an array, which can be concatenated by calling join():
var tags = $('meta[name=keywords]').attr("content");
var data = [
"http://xyz/abc/names/",
encodeURIComponent(tags),
".json?callback=showGameDetail"
].join('');
$("#demo").html(data);
Actually the concat method works on strings too (in chrome at least) but the recommended method is using the plus concatenation string operator
You are however missing some stuff
jQuery library - I assume you want that since you have $(...) in the example
encoding of the string from the keywords - I use encodeURIComponent to handle possible newlines and quotes in the keywords
.
<!DOCTYPE html>
<html>
<head>
<title>Create a URL from keywords</title>
<meta name="keywords" content="These are tags" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
function myFunction() {
var tags = $('meta[name=keywords]').attr("content");
var URL ="http://xyz/abc/names/" +
encodeURIComponent(tags) +
".json?callback=showGameDetail";
window.console && console.log(URL);
$("#demo").html(URL);
}
</script>
<body>
<p id="demo">Click the button to join two strings into one new string.</p>
<button onclick="myFunction()">Try it</button>
</body>
</html>

how to display only first 10 characters of file name that they upload in the html page

The code to print the file name is
<div id="file">'+filename+'</div>
i want only the first 10 characters of the file name and not the all. what java script function can i use as i cannot use php.
Not sure if you wanted the code for getting the DIV contents as well.
Complete example below:
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<div id="file">I want the first 10 characters</div>
<script>
$(document).ready(function() {
var div = $('#file');
var str = div.text();
var stripped = str .substr(0, 10);
alert(stripped);
});
</script>
</body>
</html>
var str = "this is isdfisdf";
console.log(str.substr(0, 10));
To get the first 10 characters from a string in JavaScript use substr()
var str = str.substr(0,10);
or using substr() in PHP :
$str = substr(str,0,10);

Load and parse xml based on string, IE

Im trying to parse an xml string in IE based on the following example: http://dean.edwards.name/weblog/2006/04/easy-xml/
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(function(){
var xml = document.createElement("xml");
xml.src = '<test><node1>Test</node1></test>';
document.body.appendChild(xml);
var xmlDocument = xml.XMLDocument;
document.body.removeChild(xml);
});
</script>
</head>
<body>
</body>
</html>
Fiddle
However, its not working. I get no errors, but nothing is happening.
Is there any way to generate an XML file on the client side in IE based on a valid xml string? Is activeX the only option?
Thanks in advance
A variant I have working is not to create an xml object, but create a wrapper div instead:
<script type="text/javascript">
$(function(){
var div, xmlDocument;
div = document.createElement('div');
div.innerHTML = '<xml><test><node1>Test</node1></test></xml>';
document.body.appendChild(div);
xmlDocument = div.firstChild.XMLDocument;
document.body.removeChild(div);
});
</script>
ActiveX is certainly one option. The code would be something like:
var xml = '<test><node1>Test</node1></test>';
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xml);
alert(xmlDoc.documentElement.nodeName);

Categories

Resources