Parsing certain kind of JSON data with jQuery - javascript

I'm a little new to JSON and I'm having some trouble figuring out how to parse a JSON file that is structured like this:
{
"list1": [
[
"id1",
"id2",
"id3",
"id4"
],
[
"value1",
"value2",
"value3",
"value4"
]
],
"list2": [
[
"id1",
"id2",
"id3",
"id4"
],
[
"value1",
"value2",
"value3",
"value4"
]
]
}
I'm using the follow jQuery to get the JSON data:
var data = $.getJSON("jsonfile.json");
Example of what I want to do:
Get an item from "list2" for "value4", but I only know what "list2" > "value2" is. How can I parse the the JSON only knowing value2 and then get the value4 result?
I'm not even sure if I'm getting the JSON as a JS object correctly. Everytime I try to alert something from "data" I get undefined (except for when I do alert(data); it says [object Object].

First of all, $.getJSON is async which means you need to do:
$.getJSON("jsonfile.json").then(function (data) {
//use your data
});
The reason you get [object Object] when you alert data is because $.getJSON returns a promise object.
Get an item from "list2" for "value4", but I only know what "list2" >
"value2" is. How can I parse the the JSON only knowing value2 and then
get the value4 result?
For the above question I do not understand it... however you can access your lists and list items like:
data.list2[1][3]; //value4

Related

How to parse JSON object into their designated types in Javascript?

When I make an API request, the API server returns me a JSON object. How do I parse the JSON object to their designated types in Javascript?
This is what is being returned to me:
{
"student_name": "Joshua",
"classes": [
"A1",
"A2",
"A3",
]
"food": {
"size": "slice",
"type": "pepperoni",
}
}
So would like to parse the array, classes, the object, food, and the string student_name, and console log them.
You need to use JSON.parse() to do it:
var myData = {
"student_name": "Joshua",
"classes": [
"A1",
"A2",
"A3",
]
"food": {
"size": "slice",
"type": "pepperoni",
}
}
var myObject = JSON.parse(myData);
console.log(myObject.student_name); //Output: Joshua
console.dir(myObject) //to see your object in console.
display a single element:
console.log(myData.classes[0]);
display all elements of an array:
var arr = myData.classes;
for(var i in arr)
{
console.log(arr[i]);
}
For more information:
About JSON.parse()
JSON.Parse() Examples
JSON is the JavaScript Object Notation, which means JSON snippets already represent JavaScript objects. You just have to parse them using:
var myObject = JSON.parse(json);
And then you can access:
var myArray = myObject.classes; //should give you an array
console.log(myArray[0]); //should print "A1"
var myFood = myObject.food //should give you a food object with size and type properties
console.log(myFood.size); //should print "slice"

pushing items to object array - javascript

Update: I'm trying to construct a table out of my data structure(ie section1) and then allow users to add rows to the table to insert more rows and save them to my datastructure.
I have an array newArr in the form of key value pairs. When somebody clicks a button, I want to be able to push the newArray into the Groups.I dont seem to be able to push into the Groups array. Chrome dev tools shows Groups as Objects and i'm not certain how to loop through and append to each item of the Groups Object. Feel free to modify the $scope.section1 to a different datastructure that could make it easier to push new items to it.
$scope.section1 = [{
"id":1, "Name": "Section 1: Inventory",
"Groups":[
{"cell" : "Number", "cellValue" : "value1"},
{"cell" : "Location", "cellValue" : "value2"},
{"cell" : "Severity", "cellValue" : "value3"}
],
"FootNotes":[
{"templateurl" : "components/section/templates/notes/section1.notes.html"}
]
}]
var newArr = {"cellValue" : "value4","cellValue" : "value5","cellValue" : "value6"}
So the output should look like
$scope.section1 = [{
"id":1, "Name": "Section 1: Inventory",
"Groups":[
{"cell" : "Number", "cellValue" : "value1", "cellValue" : "value4"},
{"cell" : "Location", "cellValue" : "value2", "cellValue" : "value5"},
{"cell" : "Severity", "cellValue" : "value3", "cellValue" : "value6"}
],
"FootNotes":[
{"templateurl" : "components/section/templates/notes/section1.notes.html"}
]
}]
You can't have two properties with the same name. You have cellValue two times for Object group. What are you trying to do?
You'd better like to change the structure itself:
...
"Groups": [
{
name: "group1",
values: ['value 1', 'value 2', 'value 3']
}
]
Then, adding one more value to group1:
$scope.section1[0].Groups.values.push('value 4')
Note than I'm trying to respect the whole structure that you already have, but I don't meaning this is the optimal way to solve your problem
$scope.section1[0].Groups.push({
"cell" : "Number",
"cellValue" : "value1",
"anotherCellValue" : "value4"
});

how to edit JSON value using Javascript or Jquery [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 years ago.
i want have a value for a specific key may be nested value also like change value of key1 to value100 or key11 to value111.
{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"map1" : {"key4":"value4",
"key5":"value5",
"key6":"value6",
"map2" :
{
"key7":"value7",
"key8":"value8",
"key9":"value9",
"map3" :
{
"key10":"value10",
"key11":"value11",
"key12":"value12"
},
"map4" :
{
"key13":"value13",
"key14":"value14",
"key15":"value15"
}
}
}
}
how to achieve this using javascript or jquery. please help me to find out the issue.
If you stored that in a variable like
var object = { *your JSON here*}
you can access it like:
object.key1
to obtain the value of your key1
If you want to get those in map2, it would be:
object.map2.key7
e.g.
If you want to change values, just do
object.key = *value*;
You can just hold your json on javascript object and edit it.
var _j ={
"key1": "value1",
"key2": "value2",
"key3": "value3",
"map1" : {"key4":"value4",
"key5":"value5",
"key6":"value6",
"map2" :
{
"key7":"value7",
"key8":"value8",
"key9":"value9",
"map3" :
{
"key10":"value10",
"key11":"value11",
"key12":"value12"
},
"map4" :
{
"key13":"value13",
"key14":"value14",
"key15":"value15"
}
}
}
};
_j.key1 = "New Key1";
$('div').html(JSON.stringify(_j));
Here is working JS Fiddle

Jquery JSON decode multiple arrays

I have this multiple set of data as array
data = [{"id": "1", "name" : "abc", "key1" : "value12 }, {"id": "2", "name" : "cde", "key2" : "value2" }.....]
I need to get this data using jQuery
json = $.parseJSON(data);
but how do I access the parsed JSON data? json.id shows the result as undefined.
Thanks
Update : Sorry I fixed the above example JSON I gave, I just quickly typed it by myself and it's not the original json I'm having trouble with. I just gave it to give an idea about the problem that I was having. Thanks for the answers :)
It isn't JSON. It isn't even JavaScript.
If you fix the syntax errors (such as the missing quotes and the missing commas between the array items) then it is an array literal (containing object literals which contain …). Don't parseJSON it (you use that on JSON texts stored in JavaScript strings).
Since it is an array. It doesn't have an id. It has a number of numerical indexes.
var someObject = data[0];
The objects stored on those indexes have ids.
var id = someObject.id;
Your json is invalid. ',' are missing between objects.
Suppose if json is :
data = [{"id": "1", "name" : "abc", "key1" : "value12" }, {"id": "2", "name" : "cde", "key2" : "value2" }]
Then you can access 'id' element using this :
data[0].id
Try this:
var data = '{"id": "1", "name" : "abc", "key1" : "value12" } , {"id": "2", "name" : "cde", "key2" : "value2"}';
var obj = JSON.parse('[' + data + ']');
alert(obj[0].id);
Here is demo
Your json is invalid,
data = [{"id": "1", "name" : "abc", "key1" : "value12" }, {"id": "2", "name" : "cde", "key2" : "value2" }.....]
Retrive using:
var id = data[0].id;
console.log(id);

Adding value to top of the JSON

I have JSON data
var json = {"options": {
"key1": "value2",
"key2": "value2",
"key3": "value3",
}
}
And I want to add one more key with value to it using JavaScript, but I want it to be on the top like this:
var json = {"options": {
"new_key": "new_value",
"key1": "value2",
"key2": "value2",
"key3": "value3",
}
}
How can I do it?
Objects do not guarantee property order in JavaScript, but arrays do. If the order really matters and you are allowed to change your JSON structure, I'd suggest to use an array instead to organize your data.
var json = {
"options": [
{"key": "key1", "value": "value1"},
{"key": "key2", "value": "value2"},
{"key": "key3", "value": "value3"}
]
};
Using this, you could push an element to the start of the array using the unshift method.
json.options.unshift({"key": "new_key", "value": "new_value"});
Although it is not required by any of the ECMAScript specs, nonetheless most implementations do retain the original order of keys in Objects, with the exception of keys with numeric values. You can see a lengthy discussion about the Chrome's implementation here: http://code.google.com/p/v8/issues/detail?id=164
If you want to utilize this, you will need to create a new Object:
var newOpts = {};
newOpts["new_key"] = "new_value";
for (var k in json.options) {
newOpts[k] = json.options[k];
}
json.options = newOpts;
However if you do actually turn your object into a JSON string, and send it to someone else, there is no guarantee that they will preserve the order when they parse the string back into an Object.
I was surprised to discover the widely used Express library for NodeJS actually relies on this behaviour for its format method.
JSON Objects have no order.
If order is important to you, consideer creating options as an array, then you can iterate and adding items in a specific order:
var json = {"options": [
{key: "new_key", value: "new_value"},
{key: "key1", value: "value2"},
{key: "key2", value: "value2"},
{key: "key3", value: "value3"},
]}
You can extend the object in the following way using vanilla JavaScript but again this won't set the order as others have noted.
extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
};
var json = {
"options": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
};
extend(json.options, {"new_key": "new_value"});
You could use the extend function the ordering of the objects would determine which parameters would be written first, but as stated by DanFromGermany there aren't many real-life cases where the order is relevant.

Categories