Reading from a JSON object via Javascript syntax [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 years ago.
I am trying to read some values from a JSON object and use them to populate an html template. I can seem to figure out the right syntax to read from the JSON file. For example, when I want to read in the first object's "role", I write:
console.log("first object: "+ ((obj[0].roles)[0]).name)
The above works and returns "first object: thing commented on".
Then when I try to read the text of the verb under the "srcLanguageSentence" within the first object, I write:
console.log("first verb: "+ ((obj[0].srcLanguageSentence.verb[2]).text)
I expect to see "first verb: comment" but that does not happen. Where is my syntax wrong here?Please see a snippet of the JSON object file below:
[
{
"description": "",
"roles": [
{
"name": "thing commented on"
},
{
"name": "commentor"
}
],
"srcLanguageSentence": {
"roles": [
{
"beginOffset": 23,
"endOffset": 30,
"name": "thing commented on",
"text": "on them"
},
{
"beginOffset": 5,
"endOffset": 7,
"name": "commentor",
"text": "We"
}
],
"text": " `` We wo n't comment on them . '' ",
"verb": {
"beginOffset": 15,
"endOffset": 22,
"text": "comment"
}
},
"tgtLanguageSentences": [
{
"roles": [
{
"beginOffset": 1,
"endOffset": 31,
"name": "thing commented on",
"text": "Weitere Aspekte der Kommission"
},
{
"beginOffset": 44,
"endOffset": 47,
"name": "commentor",
"text": "ich"
},
{
"beginOffset": 48,
"endOffset": 55,
"name": "negation",
"text": "nicht ."
}
],
"text": " Weitere Aspekte der Kommission kommentiere ich nicht . ",
"verb": {
"beginOffset": -1,
"endOffset": -1,
"sense": "COMMENT, intransitive",
"text": "kommentieren"
}
}
],
"verb": "KOMMENTIEREN"
},
]

Use:
console.log("first verb: "+ obj[0].srcLanguageSentence.verb.text)
Instead of:
console.log("first verb: "+ ((obj[0].srcLanguageSentence.verb[2]).text)
In general, you need to use the bracket notation [] when accessing an array and the dot notation (.something) when accessing a property of an object. In JSON, an array is indicated by [] while an object is indicated by {}. Those two simple rules make it easy to figure out how to access nested values typically seen in complex JSON objects.
Note that in practice, you can use bracket notation when access an object. For example, say we have this object:
var obj = { x: 10 };
I can do console.log(obj['x']) or console.log(obj.x) and either will work. This makes it possible to programmatically access an object. Say like this:
var obj = {
x: 10,
y: 30,
z: -2
};
Object.keys(obj).forEach(function(key) {
console.log(obj[key]);
});
There we loop over the keys (['x', 'y', 'z']) and can then use the bracket notation to access the values. We can't do obj.key because that would lookup key in the object -- not the value of key.

console.log("first verb: "+ obj[0].srcLanguageSentence.verb.text)

console.log("first verb: "+ ((obj[0].srcLanguageSentence.verb[2]).text) should be:
console.log("first verb: "+ obj[0].srcLanguageSentence.verb.sense.text.split(', ')[0].toLowerCase());
That's if your desired output is first verb: comment.

Related

How can I add an element in object at certain position?

I have this object:
var ages = [{
"getasafieldDetail": {
"id": "xxx",
"asaentrySet": [{
"result": "ON",
"buy": {
"username": "Dis"
},
"offerSet": [{
"createdStr": "2001-08-09 at 11:52 pm",
"value": 5.0
}]
}]
}
}];
and i want to add an element and have an output like this:
var ages = [{
"getasafieldDetail": {
"id": "xxx",
"asaentrySet": [{
"result": "ON",
"buy": {
"username": "Dis"
},
"land": "111", // THIS <<<<------------
"offerSet": [{
"createdStr": "2001-08-09 at 11:52 pm",
"value": 5.0
}]
}]
}
}];
i tried using splice but not works...
ages.splice(ages[0]['getasafieldDetail']['asaentrySet'][0]['offerSet'],0,'"land": "111"');
ages.join();
There is the handy syntax of Destructuring assignments which helps with cutting and reassembling objects.
Edit
#FireFuro99 did point to the ES6/ES2015 spec which explicitly states how to preserve/handle an object's key-order at the object's creation time.
Thus one can say ...
Every JS engine which does support Destructuring assignment has to respect too any object's key order from/at this object's creation time.
const ages = [{
getasafieldDetail: {
id: "xxx",
asaentrySet: [{
result: "ON",
buy: {
username: "Dis",
},
offerSet: [{
createdStr: "2001-08-09 at 11:52 pm",
value: 5.0,
}],
}],
},
}];
const { result, buy, ...rest } = ages[0].getasafieldDetail.asaentrySet[0];
ages[0].getasafieldDetail.asaentrySet[0] = {
result,
buy,
land: "111",
...rest,
};
console.log({ ages });
.as-console-wrapper { min-height: 100%!important; top: 0; }
Splice only works on Arrays.
To make this work, convert your Object to an Array using Object.entries(), then use splice, and then convert it back to an object using Object.fromEntries().
const entrySet = Object.entries(ages[0]['getasafieldDetail']['asaentrySet'][0]);
entrySet.splice(2,0, ["land", "111"]);
ages[0]['getasafieldDetail']['asaentrySet'][0] = Object.fromEntries(entrySet);
This will insert the key-value pair at the the specified position.
The advantage this has over the destructuring assignment is, that you can specify the index, whereas destructuring is pretty hardcoded.
ages[0]["getasafieldDetail"]["asaentrySet"][0].land = '111' will create the key land in the first object in asaentrySet and assign the value 111. Key order is not guaranteed
var ages = [{
"getasafieldDetail": {
"id": "xxx",
"asaentrySet": [{
"result": "ON",
"buy": {
"username": "Dis"
},
"offerSet": [{
"createdStr": "2001-08-09 at 11:52 pm",
"value": 5.0
}]
}]
}
}];
ages[0]["getasafieldDetail"]["asaentrySet"][0].land = '111'
console.log(ages)
When it is an array of objects you could simple, add, passing the position that you want by editing the array like the example below:
let land = {land: 1111}
let ages = [{'a':11},'2', 'wd']
let new =[]
new.push(ages[1])
new.push(land)
ages[1] = new
console.log(ages)
output:
(3) [{…}, Array(2), "wd"]
You get what you want from the array, edit it, and put back in the same position, may it can help.

How to parse/filter data from JSON file in Javascript

Is there any way to parse/filter the data present in JSON file in a Javascript file.
Basically, I am calling JSON file into my local javascript. I am having trouble in reading specific data and printing.
Can anyone please help.
JSON file contains:
{
"Data": [
{
"name": "John",
"age": 30
},
{
"joined on":"Jan 2015",
"working on": "Automation",
}
]
}
I am trying to read the above JSON file as:
var jfile = require("./Example.json");
var test = JSON.parse(JSON.stringify(jfile))
console.log(test)
I get the output like this:
{ Data:
[ { name: 'John', age: 30 },
{ 'joined on': 'Jan 2015', 'working on': 'Automation' } ] }
From the above, I am interested in accessing/filtering out only one i.e. "name". I would like to print only the value "John" to the console.
I have tried to use the ".filter" method to the JSON.parse method but it throws me an error as:
JSON.parse(...).filter is not a function
Is there any way to perform this activity?
You can access it using . dot notation
var a = {
"Data": [{
"name": "John",
"age": 30
},
{
"joined on": "Jan 2015",
"working on": "Automation",
}
]
}
console.log(a.Data[0].name)
filter is an array method.
JSON.parse(...) will not give you an array. It will give you an object with a Data property. The value of that property is an array.
JSON.parse(...).Data.filter.
You can't just ignore parts of your data structure.
If you have multiple items in your array of different shapes, you can use this
Access the Data key with json.Data
map your array to transform its items into names
apply filter(Boolean) to take out those who are undefined
In your case you'll end up with an array containing only one name John
const getName = json => json.Data.map(x => x.name).filter(Boolean);
const json = {
"Data": [{
"name": "John",
"age": 30
},
{
"joined on": "Jan 2015",
"working on": "Automation",
}
]
};
console.log(getName(json));
Your JSON's main level is an object (not an array) and only arrays have .filter method.
So filter the array under Data key:
var test = JSON.parse(JSON.stringify(jfile)).Data.filter(/*something*/);
But better if you aren't re-parse JSON:
var test = jfile.Data.filter(/*something*/);
As Quentin mentioned in his comment, What is the use of below statement ?
var test = JSON.parse(JSON.stringify(jfile))
You can directly access the name property from the response.
Try this :
var obj = {
"Data": [{
"name": "John",
"age": 30
},
{
"joined on": "Jan 2015",
"working on": "Automation"
}
]
};
// Solution 1
console.log(obj.Data.map(item => item.name).filter(Boolean));
// Solution 2
console.log(obj.Data.filter(item => item.name).map(elem => elem.name));

Filtering and counting json properties in javascript

I have a json object whose items I would like to analyze in js. When I log the json to the console, you can see that it contains the element items which holds an array of the relevant information.
console.log(json)
{current_page: 1, per_page: 100, total_entries: 106, items: Array(100)}
current_page:1
items:Array(100)
0:{id: 15814, name: "Vehicle_1001", state: "available", repair_state: "broken", network_id: 99, …}
1:{id: 16519, name: "Vehicle_1002", state: "available", repair_state: "broken", network_id: 99, …}
However, when I try to use the filter function to count the amount of records where repair_state is broken, I am returned an error:
json.filter(value => value.items.repair_state === 'broken').length
Uncaught TypeError: json.filter is not a function
What am I doing wrong and how would one count the number of items whose repair_state property is equal to broken in this case?
As i see from your console.log, json is an object where items is an array inside it, so you should apply filter on the array items. It should be,
var result = json.items.filter(value => value.repair_state === 'broken').length;
DEMO
var json= {
"current_page": 1,
"per_page": 100,
"total_entries": 106,
"items": [
{
"id": "15814",
"name": "Vehicle_1001",
"state": "available",
"repair_state": "broken"
},
{
"id": "16519",
"name": "Vehicle_1002",
"state": "available",
"repair_state": "broken"
}
]
};
var result = json.items.filter(value => value.repair_state === 'broken').length;
console.log(result);

Create nested JSON array

I'm trying to create a JSON array to send it to my web service. This is how my json should look like:
[{
"tipus": 1,
"proveidor": 3,
"atributs": {
"atribut":{
"id": 1,
"valor": 8
},
"atribut":{
"id": 2,
"valor": 500
}
}
}]
So, I have two general values "tipus" and "proveidor" and multiple "atributs" each "atribut" is composed with "id" and "valor".
When I construct the json I get this instead of what I want:
[
2:{
"tipus": 1,
"proveidor": 3,
1:{
"id": 1,
"valor": 8
},
0:{
"id": 2,
"valor": 500
}
}]
This is how I'm building the json:
// For every founded in $scope.atrb i need to create an 'atribut' element into my json
$scope.a = [];
var key;
for(key in $scope.atrb){
var newField = {
"idatributs_actiu": $scope.atrb[key].idatributs_actiu,
"nomAtribut": $scope.atrb[key].nomAtribut,
"valor": $scope.atrb[key].valor,
"idActiu": $routeParams.idTipusActiu,
"value": "",
"ordre": $scope.atrb[key].ordre,
"idatributs_generics": $scope.atrb[key].idatributs_generics
};
$scope.a.push(newField);
}
$scope.f = $scope.a;
});
var generics = {
"nom": $scope.nom,
"tipus": $routeParams.idTipusActiu,
"proveidor": $scope.proveidor.id
};
$scope.a.push(generics);
It's my first project with angular and I'm not sure if I'm building the json appropriately, basically i use an array to build a json but I don't know how to nested it 'atribut' inside 'atributs'.
The main idea is to read the 'generics' atributes and then loop through 'atributs' and read all 'atribut' element getting the properties.
Regards
Like S4beR and Kevin B told me, I just need to do an JS array. This is in my controller:
var obj = { generics: g, atributs: $scope.a };
g: it's an object with the generic properties
$scope.a: this is an array with 'atribut' objects which contais all
the properties I need save to.

get value from json when passed key is a variable [duplicate]

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.

Categories