Error while parsing JSON string using JQuery - javascript

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.

Related

Setting charset encoding in Javascript application

I am calling a SOAP service in my Javascript code, and the response of this service is correct but strings returned does not show letters with accents. So, I have a problem with encoding charset and I am trying the following actions:
1) I ensure that the HTTP response returning string data has the correct charset defined. So, I have checked with https://validator.w3.org/i18n-checker/ that the encoding charset of the URI that I am calling is "utf-8".
2) I have defined charset in the head section of html:
<meta charset='utf-8' content-type="text/xml;charset=UTF-8"/>
3) Also, I call this service with a function in module.js, I have also defined
<script src="node_modules/my_module.js" charset="utf-8"></script>
All three with the same wrong result.
I added an image with the some examples:
image with result strings, where in green square have to say 'Sant Martí de Tous', in red 'Moianès', in blue 'Santa Bàrbara', 'Montsià', in orange 'Torroella de Montgrí', etc
This is a minimum sample code to call SOAP service with tinysoap library:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' content-type="text/xml; charset=utf-8"/>
<title>Test Charset Encoding</title>
<link rel="stylesheet" href="https://js.arcgis.com/4.15/esri/themes/light/main.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="node_modules/tinysoap/tinysoap-browser-min.js"></script>
<script src="https://js.arcgis.com/4.15/"></script>
<script>
var tinySoap=this.tinysoap;
require(["esri/Map"], function(Map) {
var inputCtrl = document.getElementById("inputString"); // gironès
var outputCtrl = document.getElementById("outputString");
inputCtrl.onchange = function() {
var userTxtValue = inputCtrl.value;
var args = {nom: userTxtValue};
//console.log("[INPUT] : ",args);
//outputCtrl.innerHTML = "<br><b>Input ... </b>" + userTxtValue +"<br>";
tinySoap.createClient(url, function(err, client){
client.localitzaToponim(args, function(err, result) {
var data = result['item'];
//console.log("[OUTPUT] : ",data);
//outputCtrl.innerHTML += "<b>Output ... </b>";
//data.forEach(element => {
// outputCtrl.innerHTML += "<br> "+ element.Nom;
//});
});
});
}
});
</script>
</head>
<body>
Look for place or address ...
<input id="inputString" size="50" value=""><br>
<span id="outputString"></span>
</body>
</html>
This is the result of this process for 'gironès' as input string
There is the error: "Refused to set unsafe header", but I can not see where to set header parameters to connection.
I am still working in that problem: I have checked that strings are encoded as UTF16 with this library: https://github.com/polygonplanet/encoding.js/
using Encoding.detect(string), but Encoding.convert(string,'utf8','utf16') does not work for me, neither Encoding.convert(string,'latin1','utf16'), etc
What is the right way to define the encoding charset? Thank you

Displaying data from an array of objects inside document

Been trying to take specific data from an array of objects that for many reasons I cannot host on a server. The data is in stored as a variable in the document. This is what i've been trying so far to no success:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var users = [{"username":"nphillips7m","first_name":"Nicole","last_name":"Phillips","email":"nphillips7m#ebay.co.uk","gender":"Female","sexuality":"Networked static concept","language":"Gagauz"},
{"username":"esimpson7n","first_name":"Elizabeth","last_name":"Simpson","gender":"Female","sexuality":"Future-proofed solution-oriented definition","language":"Malay"},
{"username":"llawrence7o","first_name":"Lillian","last_name":"Lawrence","email":"llawrence7o#technorati.com","gender":"Female","sexuality":"Re-contextualized demand-driven middleware","language":"Tetum"}]
var simpson = users.find("last_name" + "Simpson")
document.getElementById("return").innerHTML = function myfunction() {
simpson;
}
</script>
</head>
<body>
<div id="return"></div>
</body>
For now I've just been trying to extract some/any data from the 'users' array, but going forward i would like to have the user search for a word and the entire 'line'/'lines' of data related to the word/words in 'users' display as results. What methods should i use to achieve this?
You have some mistakes in your code. First of all, find function accept as argument a callback function.
var simpson = users.find(a=>a.last_name=="Simpson");
If you pass function to innerHTML, you must to invoke it, like this:
document.getElementById("return").innerHTML = (function myFunction(){
return JSON.stringify(simpson);
})();
and function must return a value in order to set the HTML content (inner HTML) of result element.
var users = [{"username":"nphillips7m","first_name":"Nicole","last_name":"Phillips","email":"nphillips7m#ebay.co.uk","gender":"Female","sexuality":"Networked static concept","language":"Gagauz"},
{"username":"esimpson7n","first_name":"Elizabeth","last_name":"Simpson","gender":"Female","sexuality":"Future-proofed solution-oriented definition","language":"Malay"},
{"username":"llawrence7o","first_name":"Lillian","last_name":"Lawrence","email":"llawrence7o#technorati.com","gender":"Female","sexuality":"Re-contextualized demand-driven middleware","language":"Tetum"}]
var simpson = users.find(callback);
function callback(item){
return item.last_name=="Simpson";
}
document.getElementById("return").innerHTML = (function myFunction(){
return JSON.stringify(simpson);
})();
<body>
<div id="return"></div>
</body>
1. You need to pass the callback function in find method. The find method searches for an element in an array and returns the element if it is found. Otherwise undefined is returned. The Search Criteria is defined by a callback function. Something like
var simpson = users.find(currentValue => currentValue.last_name === "Simpson");
2. You might not require your innerHTML to be a function, instead it would be more appropriate that it points to meaningfull information like UserName Found.
document.getElementById("return").innerHTML = simpson.username;
Try the following code.
var users = [{"username":"nphillips7m","first_name":"Nicole","last_name":"Phillips","email":"nphillips7m#ebay.co.uk","gender":"Female","sexuality":"Networked static concept","language":"Gagauz"},
{"username":"esimpson7n","first_name":"Elizabeth","last_name":"Simpson","gender":"Female","sexuality":"Future-proofed solution-oriented definition","language":"Malay"},
{"username":"llawrence7o","first_name":"Lillian","last_name":"Lawrence","email":"llawrence7o#technorati.com","gender":"Female","sexuality":"Re-contextualized demand-driven middleware","language":"Tetum"}]
var simpson = users.find(currentValue => currentValue.last_name === "Simpson");
document.getElementById("return").innerHTML = simpson.username;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
</script>
</head>
<body>
<div id="return"></div>
</body>

Parsing HTML plaintext data into javascript array

So I have a very simple HTML page called Terms.html. Here is the output:
Museums, Parks, Railroads and Trains, Shopping, Theatres
and here is the code:
<!DOCTYPE html>
<html>
<body> Museums, Parks, Railroads and Trains, Shopping, Theatres </body>
</html>
Now, I am using jQuery $.get method to retrieve this html page:
<!doctype html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<script>
var tags = [ "String1", "String2"];
$.get("Terms.html", function(data, status) {
<!-- -->
$(result).html( data );
alert("Status: " + status);
});
</script>
<p>Search terms are: <span id="displayterms"></span></p>
<div id="result"><div>
</body>
</html>
What I want to do is be able to parse Museums, Parks, Railroads and Trains, Shopping, Theatres into individual strings and add them to my var tags array. Any ideas on how I can do this? Thanks
Try:
var tags = ["String1", "String2"];
var str = "Museums, Parks, Railroads and Trains, Shopping, Theatres";
arr = $.map( tags.concat(str.split(',')), function( n ) { return $.trim(n) });
console.log(arr); // Outputs the array ["String1", "String2", "Museums", "Parks", "Railroads and Trains", "Shopping", "Theatres"]
jsFiddle example
The third line splits the str on the commas and then uses jQuery's .map() function to trim the whitespace.
With the split function: http://www.w3schools.com/jsref/jsref_split.asp
This will split on any character you choose, in this case ","
tags = data.split(",");
If you don't need to support versions of IE older than 9, you could do something like this:
var tags = document.body.textContent.split(',').map(
function (s) {
return s.trim();
}
);
document.body.textContent gets the text in the body tag. This restricts your browser support, as IE didn't have this until version 9.
.split(',') takes the string and splits it into its component parts, returning an array.
.map() applies a function to everything in the array returned by .split(','), and returns an array of the results. In this case, we use it to call trim() on each string in the array, to strip leading and trailing whitespace. IE didn't have the Array.prototype.map or String.prototype.trim methods until version 9, but they're easy to polyfill. It's the textContent thing above that's trickier.
The array returned from map() is then put into your tags variable.
Instead of storing the contents as HTML, you could store them in a JSON data file.
An example JSON data file (places.json):
{
"Names": [ "Museums", "Parks", "Railroads and Trains", "Shopping", "Theatres"]
}
Then, you can change your page code to:
<script>
var tags = [ "String1", "String2"];
$.getJSON("/places.json", function(data) {
$(result).html(data);
console.log(data.Names[0]); // Outputs Museums
$.each(data.Names, function(index, value) {
tags.push(value); // add the tag to your tags list for each item in Names
});
});
</script>
This way you can store just the data you need and you won't need to parse the HTML manually.

web.py templator passed jsons not being parsed correctly in javascript

I am using web.py and templetor and passing a variable full of jsons to javascript embedded in the templetor file. These jsons are to be consumed by D3.
Python Code
for row in rs:
#z['time'] = row.gps
z['year'] = count + 2000
z['value'] = row.br
allrows.append(z)
count = count+1
if count > 5: break;
p = json.dumps(allrows)
return render.index(p)
Now this is supposed to be consumed in the templetor file:
$def with (data)
<!DOCTYPE html>
<body>
<meta charset="utf-8">
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<div id="bar-demo"></div>
<script type="text/javascript" id="bar-demo-js">
var data = JSON.parse($data)
This seems to run into errors -- (as per firefox)
SyntaxError: invalid property id
[Break On This Error]
var data = JSON.parse([{"value": 151.47999999999999, "year":...
You don't have to call JSON.parse because it is already object and not a string in JavaScript. Just var data=$data is enough.

Why doesn't JSON.parse work?

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));

Categories

Resources