I use the ajax which sends back a string..
I want to convert the responsetext into a json object to process.
I tried eval and also , but doesn't works...
Wht to do?
My code is
function handleResponse() {
if (httpa.readyState == 4) {
var response = httpa.responseText;
if (response != 'empty') {
alert(response);
var foo = eval('(' + strJSON + ')');
alert(foo);
}
}
}
// response alerts
[{
"id": "1",
"name": "Pepsodent 100g",
"selling_price": "28.75"
}, {
"id": "2",
"name": "Pepsodent 40g",
"selling_price": "18.90"
}, {
"id": "3",
"name": "Pepsodent brush",
"selling_price": "19.50"
}]
Using https://github.com/douglascrockford/JSON-js/blob/master/json2.js
you can do
JSON.parse(response, reviver)
http://www.json.org/js.html
Change strJSON to response.
Related
I want to get name value. How do I access it?
json looks like this
var result = null;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
result = JSON.parse(this.responseText);
for(var i = 0; i <= result.total_count; i++)
{
console.log(result.data[i].name);
}
}
});
This is giving me result as I want but with an error
Cannot read property 'name' of undefined in log.
You need to parse your JSON first:
const result = JSON.parse(this.responseText);
console.log(result.data[0].name);
The responseText property you use returns the response as purely text. In this case you are trying to read the data property of a String object. Since this doesn't exist it will be undefined. Next you are trying to access the 0 property of an undefined value which will result in the error you encounter.
Using the JSON.parse method will convert the string to a Javascript object which does have a data property.
Thanks #3limin4t0r for further clarifying in the comments!
This is demo json
{
"name": "mkyong",
"age": 30,
"address": {
"streetAddress": "88 8nd Street",
"city": "New York"
},
"phoneNumber": [
{
"type": "home",
"number": "111 111-1111"
},
{
"type": "fax",
"number": "222 222-2222"
}
]
}
follow this code :
<script>
var data = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';
var json = JSON.parse(data);
alert(json["name"]); //mkyong
alert(json.name); //mkyong
alert(json.address.streetAddress); //88 8nd Street
alert(json["address"].city); //New York
alert(json.phoneNumber[0].number); //111 111-1111
alert(json.phoneNumber[1].type); //fax
alert(json.phoneNumber.number); //undefined
</script>
Working with a JSON nested object and I get an error when running in the javascript console "JSON3.html:11 Uncaught SyntaxError: Invalid or unexpected token"
I've verified the JSON via https://jsonformatter.org/json-viewer and that looks ok. The output is only the text in my h2 tag. What am I missing?
Here's the code.
<!DOCTYPE html>
<html>
<body>
<h2>Testing JSON .</h2>
<p id="demo"></p>
<script>
var myJSON = '{
"LevelOne": {
"LevelTwo": {
"location": {
"campus": "SouthWest",
"building": "Biggest",
"floor": "1st",
"room": "101"
},
"quantity": "1",
"section": "ABC",
"task": "abc123456zyx"
}
}
}';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myJSON.LevelOne.LevelTwo.location;
</script>
</body>
</html>
String concatenation
String that are surrounding using " and ' cannot extend over multiple lines, so have to separate each line and then concatenate them. Example:
var myJSON = '{' +
'"LevelOne": {' +
'"LevelTwo": {' +
'"location": {' +
'"campus": "SouthWest",' +
'"building": "Biggest",' +
'"floor": "1st",' +
'"room": "101"' +
'},' +
'"quantity": "1",' +
'"section": "ABC",' +
'"task": "abc123456zyx"' +
'}' +
'}' +
'}';
console.log(myJSON);
Template Literals
In ES6, template literals were added, that allow to have strings span through multiple lines, provided you use ` instead of " or '. Example:
var myJSON = `{
"LevelOne": {
"LevelTwo": {
"location": {
"campus": "SouthWest",
"building": "Biggest",
"floor": "1st",
"room": "101"
},
"quantity": "1",
"section": "ABC",
"task": "abc123456zyx"
}
}
}`;
console.log(myJSON);
Removes the new lines from the JSON
A simple way to make the JSON 1 line tall is to do JSON.stringify(json) at the browser's console.
Use a normal JSON
You can just use the normal object notation of the JSON instead of the JSON and then if you want to you can convert it back to a string using JSON.stringify. Example:
var myJSON = {
"LevelOne": {
"LevelTwo": {
"location": {
"campus": "SouthWest",
"building": "Biggest",
"floor": "1st",
"room": "101"
},
"quantity": "1",
"section": "ABC",
"task": "abc123456zyx"
}
}
};
console.log(JSON.stringify(myJSON));
console.log(myJSON);
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).Including parsing JSON so you can access data within it, and creating JSON
Instead of using JSON data as a string you can directly add the JSON
data or use the double quote.if you are storing the JSON object of object in a variable using single quote, You just > write add the JSON data string in a single line or else use the double quote.
Example
<!DOCTYPE html>
<html>
<body>
<h2>Testing JSON .</h2>
<p id="demo"></p>
<script>
var myJSON = '{"LevelOne": {"LevelTwo": {"location": { "campus": "SouthWest","building": "Biggest","floor": "1st", "room": "101"},"quantity": "1","section": "ABC","task": "abc123456zyx"}}}';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.LevelOne.LevelTwo.location;
</script>
</body>
</html>
You can get the result.!
Another Solution
myJSON.LevelOne.LevelTwo.location is OBJECT
var myJSON =
{ LevelOne:
{ LevelTwo:
{ location:
{ campus: "SouthWest", building: "Biggest", floor: "1st", room: "101"}
, quantity: "1"
, section: "ABC"
, task: "abc123456zyx"
}
}
}
console.log ( myJSON.LevelOne.LevelTwo.location )
// ===> OBJECT
I am sending array of objects to print function but not working.
<script>
var items = [{
"id": "1",
"name": "rishi"
}, {
"id": "2",
"name": "xyz"
}];
var output = "<button type='button' onClick='print(" + items + ")'>Print</button>";
document.getElementsByTagName("body").innerHTML = output;
function print(data) {
alert(data);
}
</script>
<body>
</body>
<script>
var items = [{
"id": "1",
"name": "rishi"
}, {
"id": "2",
"name": "xyz"
}];
var output = "<button type='button' onClick='print(" + items + ")'>Print</button>";
document.getElementsByTagName("body").innerHTML = output;
function print(data) {
alert(data);
}
</script>
<body>
</body>
It should return array when I will click on print
getElementsByTagName returns a collection of elements, so that you should access the body element by index [0]
In order to see the content of objects in the alert try to convert them to strings using JSON.stringify
var items = [{
"id": "1",
"name": "rishi"
}, {
"id": "2",
"name": "xyz"
}];
items = JSON.stringify(items.map(JSON.stringify))
var output = "<button type='button' onClick='print(" + items + ")'>Print</button>";
document.getElementsByTagName("body")[0].innerHTML = output;
function print(data) {
alert(data);
}
<body>
</body>
Try
function print(data) {
alert(JSON.stringify(data));
}
Otherwise you get only data type shown Object in this case
What you might do is get the first item the getElementsByTagName returns using document.getElementsByTagName("body")[0]
Then call the function print passing items as the argument onClick=print(items)
var items = [{
"id": "1",
"name": "rishi"
}, {
"id": "2",
"name": "xyz"
}];
var output = "<button type='button' onClick=print(items)>Print</button>";
document.getElementsByTagName("body")[0].innerHTML = output;
function print(data) {
alert(JSON.stringify(data));
}
Your issue is with document.getElementsByTagName("body").innerHTML. .getElementsByTagName doesn't return a single element, it returns a HTMLCollection, which contains all body tags. Imagine if you passed "p" into the same method; it is possible that there are multiple p tags and thus you need to get a collection back, not just one single element.
Instead, you can use document.querySelector('body') which will return the first found element of <body>, which you can then use .innerHTML on.
Lastly, you'll need to stringify your items array such that it is preserved when you pass it into your print method
See example below:
var items = [{
"id": "1",
"name": "rishi"
}, {
"id": "2",
"name": "xyz"
}];
var output = "<button type='button' onClick='print("+ JSON.stringify(items) + ")'>Print</button>";
document.querySelector("body").innerHTML = output;
function print(data) {
console.log(data);
alert(data);
}
I am having trouble to display the top tracks of a searched artist using the LastFM api to get data. The api returns an object toptracks. I would like to grab details about each of the top tracks from that api data.
I am not sure if I am on the right track. Can someone take a look and let me know if I am doing something wrong?
Sample data from api:
{
"toptracks": {
"track": [{
"name": "Best I Ever Had",
"playcount": "3723918",
"listeners": "1086968",
"mbid": "00bde944-7562-446f-ad0f-3d4bdc86b69f",
"url": "https://www.last.fm/music/Drake/_/Best+I+Ever+Had",
"streamable": "0",
"artist": {
"name": "Drake",
"mbid": "b49b81cc-d5b7-4bdd-aadb-385df8de69a6",
},
"#attr": {
"rank": "1"
}
},
{
"name": "Forever",
"playcount": "1713492",
"listeners": "668998",
"url": "https://www.last.fm/music/Drake/_/Forever",
"streamable": "0",
"artist": {
"name": "Drake",
"mbid": "b49b81cc-d5b7-4bdd-aadb-385df8de69a6",
},
"#attr": {
"rank": "2"
}
}
}
function renderTracks(trackArray) {
function createHTML(track){
return `<h1>${track.name}</h1>
<h2>${track.artist[0]}</h2>
<h3>${toptracks[1].rank}</h3>
<h3>${track.playcount}</h3>`;
};
trackHTML = trackArray.map(createHTML);
return trackHTML.join("");
};
var searchString = $(".search-bar").val().toLowerCase();
var urlEncodedSearchString = encodeURIComponent(searchString);
const url = "lastFMwebsite"
axios.get(url + urlEncodedSearchString).then(function(response) {
// createHTML.push(response.data.track);
// $(".tracks-container").innerHTML = renderTracks(response.data.track);
// comented out old code above
createHTML.push(response.toptracks.track);
$(".tracks-container").innerHTML = renderTracks(response.toptracks.track);
})
I've notice that you have not parsed the response:
axios.get(url + urlEncodedSearchString).then(function(response) {
var parsed = JSON.parse(response);
$(".tracks-container").innerHTML = renderTracks(parsed.toptracks.track)
});
Another correction that I can suggest is to change the track.artist[0] to track.artist["name"] once this property returns an object instead of an array.
And about this: <h3>${toptracks[1].rank}</h3>. You will be not able to access that property because at your function you are providing just the trackproperty.
In this case you have two options: provide the whole response array or add a new parameter providing this.
function renderTracks(trackArray) {/**...*/};
//...
$(".tracks-container").innerHTML = renderTracks(parsed.toptracks)
Or
function renderTracks(trackArray, toptracks) {/**...*/};
//...
$(".tracks-container").innerHTML = renderTracks(parsed.toptracks.track, parsed.toptracks)
I hope this can help you :)
Your input JSON is not valid. You'll need to format it correctly. Once the data is correct:
createHTML.push(response.toptracks.track[0])
or
let i = 0;
for(; i < response.toptracks.track.length; i++){
createHTML.push(response.toptracks.track[i]);
}
I'm trying to parse a JSON message that my page gets through an AJAX response however, it keeps throwing the following error and I have no clue why:
"SyntaxError: JSON.parse: expected ',' or ']' after array element of the JSON data"
Here is what my page's javascript looks like:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var Response = JSON.parse(xhttp.responseText);
}
}
And here is what the JSON the server returns looks like:
{
"Error": "",
"ClientInfo": [{
"ID": 1,
"Name": "Bill"
}, {
"ID": 2,
"Name": "Sally"
}]
}
Any idea what I'm doing wrong? JSON validators say it's valid JSON....
UPDATE
It's that Error: key that's making the parser vomit it back out. See the demo.
Updated demo to include the JSON with Error: to compare results. Unfortunately, I had to comment out the console logged the error JSON because the debugger picked up on the Script error immediately. Fortunately, the demo still functions so you can ignore the initial error after loading.
TEST 1
Try the info button first. [Result: Sally]
Next click the error0 button. [Result: Sally]
Then try the error1 button. [Result: undefined]
So it seems to parse if you:
Remove the Error:""
OR
Place the Error: "" inside the array.
TEST 2
Copy the info JSON then validate it. JSONLint
When you use JSONLint, you must strip it:
{
"ClientInfo": [
{
"ID": 1,
"Name": "Bill"
},
{
"ID": 2,
"Name": "Sally"
}
]
}
Now copy the error JSON and validate it.
{
"Error": "",
"ClientInfo": [{
"ID": 1,
"Name": "Bill"
}, {
"ID": 2,
"Name": "Sally"
}]
}
Both of them should be valid, yet the debugger and the parser reject the error JSON.
Snippet
// Prepare JSON
var info =
'{"ClientInfo": [' +
'{"ID": 1, "Name": "Bill"},' +
'{"ID": 2, "Name": "Sally"} ]}';
var error0 =
'{"ClientInfo": [' +
'{"ID": 1, "Name": "Bill"},' +
'{"ID": 2, "Name": "Sally"},' +
'{"Error": ""} ]}';
var error1 =
'{"Error": ""},' +
'{"ClientInfo": [' +
'{"ID": 1, "Name": "Bill"},' +
'{"ID": 2, "Name": "Sally"} ]}';
// Create a function that parses JSON Object
function JSONObj(json) {
var jsonObj = JSON.parse(json);
return jsonObj;
}
// A function that logs results one at a time so we can compare results
function processLog(result) {
console.log('Result: ' + result);
}
/* Test info and errors */
var lastClient = JSONObj(info).ClientInfo[1].Name;
var errorA = JSONObj(error0).ClientInfo[1].Name;
var errorB = JSONObj(error1).ClientInfo[1].Name;
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<ol>
<li>Remove this: <pre><code>"Error": "",</code></pre>
</li>
<li>Separate into segments (see script)</li>
<li>Wrap each segment with single quotes `'`</li>
<li>Add a `+` after each segment</li>
</ol>
<button onclick="processLog(lastClient);">info</button>
<button onclick="processLog(errorA);">error0</button>
<button onclick="processLog(errorB);">error1</button>
Json parser takes in json string and parses it. You already have a json object