Can a JSON array contain Objects of different key/value pairs. From this tutorial, the example given for JSON array consists of Objects of the same key/value pair:
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
]
}
If I want to change it to have different key/value pairs inside the JSON array, is the following still a valid JSON?
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"fruit": "apple"
},
{
"length": 100,
"width": 60,
"height": 30
}
]
}
Just want to confirm this. If so, how can I use JavaScript to know if the JSON "example" field contains the first homogeneous objects or the second heterogeneous objects?
You can use any structure you like. JSON is not schema based in the way XML is often used and Javascript is not statically typed.
you can convert your JSON to a JS object using JSON.parse and then just test the existence of the property
var obj = JSON.parse(jsonString);
if(typeof obj.example[0].firstName != "undefined") {
//do something
}
It doesn't matter you can mix and match as much as you want.
You could just test it
typeof someItem.example !== 'undefined' // True if `example` is defined.
It's perfectly valid JSON. Personally I prefer this syntax better, because it reads easier:
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"fruit": "apple"
},
{
"length": 100,
"width": 60,
"height": 30
}
]
}
As to answer your second question, you can read data from a JSON string by using var data = JSON.parse(datastring);. Then simply use it by calling data.property.secondlevel. Any variable can be an object, array, string or number, allowing for nested structures.
You are free to do what you want with the contents of the array. Jus remember about this before you try to iterate an access properties of each item in your array.
one thing: you won't be able to deserialize this to anything else than an array of object in your server side, so don't have surprises later.
as a hint, maybe you could include a common field in the objects specifying the "type" so later is easy to process.
var array = [{"type":"fruit", "color":"red"},
{"type":"dog", "name":"Harry"}];
var parser = {
fruit:function(f){
console.log("fruit:" + f.color);
},
dog: function(d){
console.log("dog:"+d.name);
}};
for(var i=0;i<array.length;i++){
parser[array[i].type](array[i]);
}
Related
I have a JSON file with order data. The JSON file is formatted like this:
{
"orders": [
{"name": "Peter", "email": "peter#aol.com"}
{"name": "David", "email": "david#aol.com"}
{ "name": "George", "email": "george#aol.com"}
]
}
As you can see; all the data is part of a branch called "orders" and then each order is its own branch, but the branch doesn't have a name.
I am trying to generate a list of the "name"s in the dataset.
With a simplified dataset, I would do something like:
$(data).each(function(i, name){
$('#namesText').append($("li")
.append($("li").append(name.name))
});
})
This however doesn't work as the data is not in the first level of the tree.
My question is, how do I go down levels when the levels don't have a name?
This sounds like a DFS problem where each object has keys that can possibly be a primitive data type or another object. Since the name field could be at any level in this given constraint you need to solve for, I would say use DFS algo where it traverses each key in the object and if there is another object, look into that until you find a name field. Better solution is to redesign the data structure so that you are guaranteed to know which level and location the name field is at any time.
If you want a list of the name property from the elements of the orders array you could use Array.map:
const names = myJson.orders.map(o => o.name);
Try
namesText.innerHTML= data.orders.map(p=>`<li>${escape(p.name)}</li>`).join``
var data = {
"orders": [
{
"name": "Peter",
"email": "peter#aol.com",
},
{
"name": "David",
"email": "david#aol.com",
},
{
"name": "George",
"email": "george#aol.com",
}
]
}
namesText.innerHTML= data.orders.map(p=>`<li>${escape(p.name)}</li>`).join``
<ul id="namesText"></ul>
I would like to be able to type in "Hammerhead" to call the "Hammerhead Shark" object without its full name. Is this possible and if so how?
I tried using array.indexOf(string) though it doesn't really seem to help since it requires an exact match such as typing "Hammerhead Shark"
JS:
const JSON = require('animals.json');
var animals = Object.keys(JSON);
if (animals.indexOf("Hammerhead")) {
console.log(JSON["Hammerhead"].name);
}
JSON:
{
"Hammerhead Shark": {
"name": "Shark",
"age": "300"
},
"Duck": {
"name": "Duck",
"age": "1000"
}
}
I expect the output to be "Shark" instead of undefined.
It seems you want to get access the value in object. By its partial name.
Get the entries of object using Object.entries()
Find the key which includes() the given partial key.
return the second element of the found entry.
const obj = { "Hammerhead Shark": { "name": "Shark", "age": "300" }, "Duck": { "name": "Duck", "age": "1000" } }
function getValueByPartialKey(obj,key){
return (Object.entries(obj).find(([k,v]) => k.includes(key)) || [])[1]
}
console.log(getValueByPartialKey(obj,"Hammerhead"))
You can use string.includes(word) to return the name that matches the string that you're searching for, along with Array.filter iterates over the values too, and returns the result(s) you want.
Consider a JSON like this:
[{
"type": "person",
"name": "Mike",
"age": "29"
},
{
"type": "person",
"name": "Afshin",
"age": "21"
},
{
"type": "something_else",
"where": "NY"
}]
I want to search in the JSON value with a key (for example type='person') and then select a whole object of matched item in JSON. For example when I search for type='person' I expect this value:
[{
"type": "person",
"name": "Mike",
"age": "29"
},
{
"type": "person",
"name": "Afshin",
"age": "21"
}]
Because it's a really big JSON value, I don't want to do a brute-force search in all nodes, so I think the only way is using Regular Expressions but I don't know how can I write a Regex to match something like above.
I'm using NodeJs for the application.
Using underscore.js#where:
var results = _(yourObject).where({ type: 'person' })
If your data set is very very big [e.g. 10k or so], consider filtering / paginating stuff server side.
Plain javascript :
var results = dataset.filter(function(p) {
if(p.type == 'person')
return true;
});
If the requirement is to scan multiple times through the collection, the following one time construction overhead might be of worth.
Use hashing based on values of type.Convert the current data structure to hash map.
var hashMap ={
};
hashMap['person'] =[{},{}];
Hope this helps you.
Use
$.grep(jsonarrayobj,function(n, i){
if(n.type==="person")
{}
})
This is my sample JSON file , which im trying to parse and read the values ....
C = {{
"Travel": {
"ServiceProvider": {
"Name": "SRS",
"Rating": "3 stars",
"Rates": "Nominal",
"Features": {
"OnlineBooking": "Yes",
"SMS_Ticket": "No"
},
"UserDetails": {
"Name": "Jack",
"Age": "33",
"Gender": "Male"
}
},
"BusProvider": {
"Name": "SRS",
"Rating": "3 stars",
"Rates": "Nominal",
"Features": {
"OnlineBooking": "Yes",
"SMS_Ticket": "No"
},
"UserDetails": {
"Name": "Jack",
"Age": "33",
"Gender": "Male"
}
}
}
}
I'm pretty new to JS , and i need to access the nested elements in a generic fashion.
Im not able to extract the details properly. Im getting stuck accessing nested the child elements.
The problem for me is that i wont always know the names of the "key's' to acess them , the JSON will be dynamic , hence i need a generic mechanism to acess the nested child elements. The Nesting can go upto 3 -4 levels.
what notation do we use to access the key / value pairs when the nesting is deep.
Any Help would be appreciated.
ater desirializing your object you can do this
var resultJSON = '{"name":"ricardo","age":"23"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
//display the key
alert(k + ' is the key)
}
you can do it using recursively offcourse like this - Link Here
the way is the same just adapt to your example
For dynamic access you can use brackets notation i.e. var json = {nonKnown: 1}; now you can access it like that:
var unknowPropertyName = "nonKnown";
var value = json[unknownPropertyName];
But if you can not even define dynamically name of the property, then you should use
for(variableName in json){
if(json.hasOwnProperty(variableName)){
console.log(variableName);
}
}
You should get the basic idea from this. Good luck
I have a working version of a function to loop through a single array in a JSON object, e.g.
[{
"Name": "John",
"Surname": "Johnson"
}, {
"Name": "Peter",
"Surname": "Johnson"
}]
sample function:
function FindName(NameToFind, data1) {
objData = JSON.parse(data1);
for (var i = 0; i < objData.length; i++) {
var Name = objData[i].Name;
if (Name == NameToFind) {
alert("found!");
}
}
}
Now I need to change this function to allow for either single OR multiple arrays e.g.
{
"Table1": [{
"Name": "John",
"Surname": "Johnson"
}, {
"Name": "Peter",
"Surname": "Johnson"
}],
"Table2": [{
"Name": "Sarah",
"Surname": "Parker"
},
{
"Name": "Jonah",
"Surname": "Hill"
}
]
}
Is there a way to determine whether the object has 1 array (like in first example) or more than one arrays (like in 2nd example), and any advice/guidance on how to extend the function to be able to loop through all the items whether it has 1 array or multiple arrays?
Your first object is an array, the second one isn't.
You can test if your argument is an array, or even just test
if (objData[0]) // that's an array
EDIT :
if you want to iterate over all properties of a (just json decoded) object, when it's not an array, you can do this :
for (var key in objData) {
var value = objData[key];
// now use the key and the value
// for example key = "Table1"
// and value = [{"Name":"John","Surname":"Johnson"}, ... ]
}