parse json and output in html - javascript

I want to parse a json file and output in html by using javascript
here is my json file
{"quiz":[
{
"quizName":"Quiz 1",
"question": [
{
"text": "1+1?",
"choiceA": "1",
"choiceB": "2",
}
]
},
{
"quizName":"Quiz 2",
"question": [
{
"text": "2+2?",
"choiceA": "3",
"choiceA": "4",
}
]
}
]}
here is my html
<body>
<div id="placeholder"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('data.json', function(data) {
var output="<ul>";
for (var i in data.quiz) {
output+="<li>" + data.quiz[i].quizName+"</li>";
}
output+="</ul>";
document.getElementById("placeholder").innerHTML=output;
});
</script>
</body>
I want to display all the "quizName" in a list format like this
Quiz 1
Quiz 2
But by code doesn't output anything.
I am new to json and javascript, I don't know whether the json file is not correct or the javascript is not correct. Thanks.

You can't have commas after the last items of an object in a JSON file.
Change:
"choiceB": "2",
To this:
"choiceB": "2"
Do the same for choiceA": "4",

if u r not sure with the Json is right or wrong you can check here online json Parser or jsonEditor
you have extra commas
this is the correct Json
{"quiz":[
{
"quizName":"Quiz 1",
"question": [
{
"text": "1+1?",
"choiceA": "1",
"choiceB": "2"
}
]
},
{
"quizName":"Quiz 2",
"question": [
{
"text": "2+2?",
"choiceA": "3",
"choiceB": "4"
}
]
}
]}
ALso parsing it REFER parsing in fiddle
Hope this Helps

Remove extra commas in your json file at line numbers 9 and 19.

All you need it's do one more loop..
var output="<ul>";
for (var i in dataset) {
for (var j in dataset[i])
{
output+="<li>" + dataset[i][j].quizName+"</li>";
}
}
output+="</ul>";
document.getElementById("placeholder").innerHTML=output;
here you go: http://jsfiddle.net/baximilian/qpJjN/

Related

Parse nested JSON Response Javascript

I know there are several threads on this subject but I've looked through over 30 threads without success.
I have managed to parse a JSON response so it looks like this:
{
"1": {
"id": "1",
"name": "Fruit",
.
.
.
"entities": {
"1": {
"id": "1",
"name": "blue bird",
.
.
.
"status": "1"
},
"2": {
using this code
let json = JSON.parse(body);
console.log(json);
Now I want to access the "id", "name" etc. AND the "id" and "name" for the "entities" tag.
So far I have tried:
console.log(json[0]);
console.log(json.id);
which both returns undefined
I have also tried
console.log(json[0].id);
which gives an error
Any ideas?
In this instance, your first key is 1, so you can access it with json[1].
const json = {
"1": {
"id": "1",
"name": "Fruit"
},
"2": {
"id": "2",
"name": "Veggies"
}
};
console.log(json[1]);
In this json, you can reach the id by
json.1.id
But I think that first of all your json is not correctly written, you should have something like
{
"elements": [
{ "id" : 1, "name" : "fruit" },
{ "id" : 2, "name" : "vegetable" }
]
}
like that, json.elements is a collection/array, and you can loop, count, or any other things you will not be able to do because your json looks like a super heavy list of different properties ( he doesn't know that json.1 and json.2 are the same type of objects.
const jsonData = JSON.parse(body);
for (const i in jsonData) {
for (const j in jsonData[i]) {
console.log('${i}: ${jsonData[i][j]}');
}
}

How i can include json file with array in to javascript file?

i have html file with javascript, app for driving tests and 2 json files: Categories of name of test and questions with answer it self. this json is dump of sqlite database. example output below.
[
{
"cat_id": "1",
"cat_name": "Общие понятия",
"cat_score": "2"
},
{
"cat_id": "2",
"cat_name": "Обязанности водителя",
"cat_score": "7"
},
{
"cat_id": "3",
"cat_name": "Cостояние здоровья водителя",
"cat_score": "1"
}
]
in my engine.js everything works but my questions and categories files are not loaded. i don't know how to load then and parse to array or variable to use it in script.
for example in php i have
require and include or file_get_content but how i need to load
So i found how to load but it not working
function load() {
var someData_notJSON = JSON.parse(data);
console.log(someData_notJSON);
}
my html file is
<script type="text/javascript" src="./Categories.json"></script>
<script type="text/javascript" src="./Questions.json"></script>
in your case you're trying to parse JSON from undefined data.
function load(data) {
var someData_notJSON = JSON.parse(data);
console.log(someData_notJSON);
}
load(`[
{
"cat_id": "1",
"cat_name": "Общие понятия",
"cat_score": "2"
},
{
"cat_id": "2",
"cat_name": "Обязанности водителя",
"cat_score": "7"
},
{
"cat_id": "3",
"cat_name": "Cостояние здоровья водителя",
"cat_score": "1"
}
]`);

Can't retrieve data from JSON in Javascript. The json is passed from php

I have a problem and i search for a solution, but i can't find it. I have this Json:
[
{
"name": "Pippo (74)",
"price": "1",
"latitudine": "10.32562",
"longitudine": "44.8003686"
},
{
"name": "pluto",
"price": "2",
"latitudine": "10.32562",
"longitudine": "44.8003686"
}
]
I want retrieve data from the Json (named msg):
num = msg.length;
document.write (num);
document.write (msg[0].name);
But it don't work! Can you help me?
You might use this parse json.
http://api.jquery.com/jquery.parsejson/
var output = jQuery.parseJSON( '[
{
"name": "Pippo (74)",
"price": "1",
"latitudine": "10.32562",
"longitudine": "44.8003686"
},
{
"name": "pluto",
"price": "2",
"latitudine": "10.32562",
"longitudine": "44.8003686"
}]' );
var list = output.data;
$.each(list,function(i,item){
console.log(item.name);
});
you can use var parsedMsg = JSON.parse(msg); to transform to a pure JS object. Then run your script. You also have a typo in 'length'
A shot in the dark here, but guessing your JSON needs to be parsed:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
var parsedMsg = JSON.parse(msg);
then you can do whatever you like with the data:
num = parsedMsg.length;
console.log(num);
console.log(parsedMsg[0].name);

Converting JSON/JS Object to array

I have a JSON response from my API that is structured like so:
{
"data": [
{
"id": "1", "name": "test"
},
{
"id": "2", "name": "test2"
}
]
}
When I reference data I get the array with each record. I need the curly braces to be brackets due to a plugin I am using requiring it to be an array.
Desired output:
[
["1", "test"],
["2", "test"]
]
How can I convert the above JSON to this?
Edit:
This turned out to be a problem with a plugin I was using, and I knew how to do this fine all along. Thought I was going crazy but my code was fine, some plugin was screwing things up.
You can do this using Array.prototype.map
var arr = json.data.map(function(x){
return [x.id, x.name];
});
Something like this maybe: http://jsfiddle.net/3gcg6Lbz/1/
var arr = new Array();
var obj = {
"data": [
{
"id": "1", "name": "test"
},
{
"id": "2", "name": "test2"
}
]
}
for(var i in obj.data) {
var thisArr = new Array();
thisArr.push(obj.data[i].id);
thisArr.push(obj.data[i].name);
arr.push(thisArr);
}
console.log(arr);

Trouble parsing json with node.js

I wrote a quick script to parse two fairly large json file (~17k records) to do a comparison of the two. I have confirmed they are both valid json (via jsonlintpro) and the same format. (The source is the same so this should be a given. But, I always assume the mistake is mine. And I still do. Just somewhere else.) However, the parsed file just outputs [object, Object]. I'm wondering what the cause could possibly be?
The json format is like this small snippet (anonymized of course):
[
{
"id": "1234",
"name": "Name1",
"url": "https://localhost/Name1",
"date_created": "2013-07-05T18:47:05Z",
"date_cancelled": "",
"props": [
{
"id": "54321",
"type": "Client",
"value": "General Store"
},
{
"id": "65432",
"type": "Contact_Name",
"value": "Joe Smith"
}
]
},
{
"id": "23456",
"name": "Name2",
"url": "https://localhost/Name2",
"date_created": "2014-02-27T17:46:43Z",
"date_cancelled": "",
"props": [
{
"id": "34567",
"type": "Client",
"value": "Bait Shop"
}
]
}]
And here is the pertinent code:
var _ = require('underscore');
var recs = require('./prod.json');
printArr(recs);
console.log(recs.length);
function printArr(arr) {
arr.forEach(function(item) {
console.log(item + ", ");
});
}
Any guidance would be greatly appreciated.
UPDATE:
Ok, so apparently the issue is with my printArr function. I'm not sure what I'm doing wrong there. I'd like to figure it out because I want to expand upon that so I can print selectively.
the parsed file just outputs [object, Object].
This is the expected behavior BECAUSE you are concatenating an object with a string.
Try console.log(item) instead
console.log(item); should indeed print [object, Object], did you try to output its properties instead?
function printArr(arr) {
arr.forEach(function(item) {
console.log( item.id, item.name, item.url, item.date_created, item.date_cancelled, item.props, ';');
});
}
Just export the value from the prod.json file.
prod.json file
module.exports = [
{
"id": "1234",
"name": "Name1"
},
{
"id": "1234",
"name": "Name1"
}]
elsewhere
var recs = require('./prod.json')
console.log(recs)

Categories

Resources