This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 7 years ago.
I am trying to write a JSON file using JQuery. I am attempting to use a javascript object as a json key however it does not run. My code is:
var lvl = 2;
$.getJSON( "json/levels.json", function(levels) {
levels.level.push({
lvl:[{
"Test": "some text"
}]
}
);
This outputs:
{
"level": [{
"lvl": [{
"Test": "Some Text",
}]
}]
}
However, it should be returning:
{
"level": [{
"2": [{
"Test": "Some Text",
}]
}]
}
What am I doing wrong?
Thanks
Nick
To use the value of the variable as the key of an object, try this:
$.getJSON( "json/levels.json", function(levels) {
var obj = {};
obj[lvl] = [{ "Test": "some text" }];
levels.level.push(obj);
);
Related
This question already has answers here:
Safely turning a JSON string into an object
(28 answers)
Adding a new array element to a JSON object
(6 answers)
Closed last month.
I have the following variable holding a json array.
let requestJson = '{ "data": [ { "type": "Type1", "value": "MyValue" } ] }';
I would like to add a property called "Id" to the above object inside data array. I expect to get something like;
{ "data": [ { "type": "Type1", "value": "MyValue", "id": "123" } ] }
How can I achieve this? I tried the following:
requestJson["data"][0]["id"] = '123';
But when I print requestJson["data"] I'm getting undefined. Would appreciate any help in appending the "Id" attribute to the object inside the array above. Thanks in advance.
You need to parse your string to convert it to an Object and after that you can manipulate the data attribute
let requestJson = '{ "data": [ { "type": "Type1", "value": "MyValue" } ] }';
const parsedObject = JSON.parse(requestJson)
parsedObject.data[0].id = 1
console.log(parsedObject)
This question already has answers here:
Remove property for all objects in array
(18 answers)
How to get a subset of a javascript object's properties
(36 answers)
How to map more than one property from an array of objects [duplicate]
(7 answers)
Closed 2 years ago.
I am trying to figure out if I can send only relevant javascript info to the frontend from the backend because I want to hide things like ID, and others when my frontend makes a request.
To put things in perspective, here is a dummy code.
[
{
"_id": "215874514845452155",
"greeting":"Hello there"
},
{
"_id": "181474545841541515",
"greeting": "General Kenobi"
},
]
when requesting, I want to get result like:
[
{
"greeting": "Hello there"
},
{
"greeting": "General Kenobi"
},
]
I am still learning stuff and I know about loop function but I want to know if there is some neat trick to it. I am coming from R programming, we hate loops.
Use Array.prototype.map:
const input = [
{
"_id": "215874514845452155",
"greeting":"Hello there",
"other":"foo"
},
{
"_id": "181474545841541515",
"greeting": "General Kenobi",
"other":"bar"
},
];
const result = input.map(({greeting,other}) => ({greeting,other}));
console.log(result);
The above is a shorthand way of writing this:
const input = [
{
"_id": "215874514845452155",
"greeting":"Hello there",
"other":"foo"
},
{
"_id": "181474545841541515",
"greeting": "General Kenobi",
"other":"bar"
},
];
const result = input.map(x => {
return {
greeting: x.greeting,
other: x.other
}
});
console.log(result);
This question already has answers here:
How to Create a form from a json-schema? [closed]
(10 answers)
Create html select with optgroup from json
(1 answer)
Create HTML form from JsonData and make it editable
(2 answers)
JQuery - Create input with attributes from JSON
(2 answers)
Closed 5 years ago.
I have a json file:
{
"questions": [
{
"title": "01. q1",
"type": "dropdown",
"options": [
{
"1",
"2",
"3"
}
]
},
{
"title": "q2",
"type": "multiple_choice",
"options": [
"1",
"2",
"3",
"4",
"5"
]
},
And I'm trying to write a for loop in a js file in order to go through the data, and if the question type is "dropdown", display an html dropdown selectors, "multiple choice" would get buttons, etc:
console.log = function(message) {
document.getElementById('q_1').innerHTML = message;
};
console.log2 = function(message) {
document.getElementById('q_2').innerHTML = message;
};
$.getJSON("generated.json", function(json)) {
for (var i = 0; i<json.questions.length; i++) {
if(json.questions[i].type=="drop_down") {
}
}
}
I'm really confused as to how to do this dynamically and not hard code most of the code. Is there a way for this to be written concisely without having to write out every option/question in an html file and just read and generate questions from the json file?
this is the way you can use it :
var data = [
{
"title": "01. q1",
"type": "dropdown",
"options": ["1","2","3"]
},
{
"title": "q2",
"type": "multiple_choice",
"options": ["1","2","3","4","5"]
}
];
$(document).ready(function(){
$(".hello").append("<p>hello</p>")
var s ="" ;
for(var i=0;i<data.length ; i++){
if(data[i].type == "dropdown"){
s += "<p>dropdown</p>";
}
else if(data[i].type == "multiple_choice"){
s += "<p>multiple_choice</p>"
}
}
$(".hello").append(s);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hello">
</div>
This question already has answers here:
draw google graph from json [closed]
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Parse JSON in JavaScript? [duplicate]
(16 answers)
How do I enumerate the properties of a JavaScript object? [duplicate]
(14 answers)
Closed 8 years ago.
hi i have generated following json , can i iterate through this
i have validated this josn using some sites
following is just example there can be more section like MATHS, LOGICAL REASONING ,ENGLISH
they can also have their individual types
{ "MATHS": [
{
"Section": "MATHS",
"Type": "INCORRECT",
"Count": "5"
},
{
"Section": "MATHS",
"Type": "NOT SOLVED",
"Count": "20"
}
],
"LOGICAL REASONING": [
{
"Section": "LOGICAL REASONING",
"Type": "CORRECT",
"Count": "1"
},
{
"Section": "LOGICAL REASONING",
"Type": "INCORRECT",
"Count": "4"
},
{
"Section": "LOGICAL REASONING",
"Type": "NOT SOLVED",
"Count": "20"
}
]
}
i have searched on may question on stack overflow but none of them can help me
Your JSON has 2 top-level elements. So, you can't logically iterate across the entire document (without flattening it).
But you can iteration across the "MATHS" and "LOGICAL REASONING" elements.
For example, using underscore:
_(data.MATHS).each(function(item) {
var section = item.SECTION;
var type = item.TYPE;
var count = item.COUNT;
// Now do something with them
});
Note the different access method to the 'LOGICAL REASONING' element, because of the space.
_(data['LOGICAL REASONING').each(function(item) {
var section = item.SECTION;
var type = item.TYPE;
var count = item.COUNT;
// Now do something with them
});
If you wanted all the data together, one way of doing it would be:
var flattened = _.union(data.MATHS, data['LOGICAL REASONING']);
_(flattened).each(function(item) {
// Process...
});
Check out the underscore docs for some more information about the possibilities. Many ways to skin a cat.
http://underscorejs.org/
Cheers.
This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
I am creating a list by fetching values from a JSON file. It is a nested JSON and the list items are- "Thriller","Fiction" which are basically keys for the next level.
on click of the item I'm passing its name(i.e. Thriller/fiction) to another function...
var val = thriller.
Now I need to fetch the value(i.e. "book" & bookname) corresponding to the passed key in this new function. I'm not able to do so using dot operator-
data.library.val not working..
If anybody has worked on something similar..please help..
JSON:
{ "library": [
{
"Thriller": [
{ "book": "ABC" },
{ "book": "DEF" }
]
},
{
"Fiction": [
{ "book": "GHI" },
{ "book": "JKL" }
]
},] }
Code snippet:
$.getJSON('resources/abc.json', function(data){
var i = data.library;
$("#menuList1").css('display','block');
$(i).each(function(key, value){
$.each(value, function(key, value){
console.log(key);
$("#menuList1").append(''+key+'');
});
}); });
Use data.library[key]
MDN Documentation
Your Json is not valid, this },] specially. A good version :
{
"library": [{
"Thriller": [{
"book": "ABC"
}, {
"book": "DEF"
}]
}, {
"Fiction": [{
"book": "GHI"
}, {
"book": "JKL"
}]
}]
}
you can refer the website http://jsonlint.com for validating your json.