How to parse/filter data from JSON file in Javascript - 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));

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.

Cypress cy.write push new items to an array throws "push is not a function" error

Using the same code from https://docs.cypress.io/api/commands/writefile.html#Flags
const filename = '/path/to/list.json'
cy.readFile(filename).then((list) => {
list.push({ item: 'example' })
// write the merged array
cy.writeFile(filename, list)
})
#system throws:
list.push is not a function
fixture file:/path/to/list.json
{
"details": {
"name": "abc",
"age": 20
}
}
expecting the list.json output as
{
"details": {
"name": "abc",
"age": 20
},
"item": "example"
}
Has anyone tried to append an existing JSON file with the above code snap?
If so please share with me your experience.
Thanks
.push() is for arrays, but you have an object in your JSON file. Use list.item ='example'; to set a new property on an object.

Filter out objects in array if one value is the same

I am fetching data from an api that, sometimes, gives me multiple objects with the same values, or very similar values, which I want to remove.
For example, I might get back:
[
{
"Name": "blah",
"Date": "1992-02-18T00:00:00.000Z",
"Language": "English",
},
{
"Name": "blahzay",
"Date": "1998-02-18T00:00:00.000Z",
"Language": "French",
}, {
"Name": "blah", // same name, no problem
"Date": "1999-02-18T00:00:00.000Z", // different date
"Language": "English", // but same language
},
]
So I want to check that no two objects have a key with the same "Language" value (in this case, "English").
I would like to get the general process of filtering out the entire object if it's "Language" value is duplicated, with the extra issue of not having the same number of objects returned each time. So, allowing for dynamic number of objects in the array.
There is an example here:
Unexpeected result when filtering one object array against two other object arrays
but it's assuming that you have a set number of objects in the array and you are only comparing the contents of those same objects each time.
I would be looking for a way to compare
arrayName[eachObject].Language === "English"
and keep one of the objects but any others (an unknown number of objects) should be filtered out, most probably using .filter() method along with .map().
The below snippets stores the languages that have been encountered in an array. If the current objects language is in the array then it is filtered out. It makes the assumption that the first object encountered with the language is stored.
const objs = [
{
"Name": "blah",
"Date": "1992-02-18T00:00:00.000Z",
"Language": "English",
},
{
"Name": "blahzay",
"Date": "1998-02-18T00:00:00.000Z",
"Language": "French",
}, {
"Name": "blah", // same name, no problem
"Date": "1999-02-18T00:00:00.000Z", // different date
"Language": "English", // but same language
},
],
presentLanguages = [];
let languageIsNotPresent;
const objsFilteredByLanguage = objs.filter(function (o) {
languageIsNotPresent = presentLanguages.indexOf(o.Language) == -1;
presentLanguages.push(o.Language);
return languageIsNotPresent;
});
console.log(objsFilteredByLanguage);
You could take a hash table and filter the array by checking Name and Language.
var array = [{ Name: "blah", Date: "1992-02-18T00:00:00.000Z", Language: "English" }, { Name: "blahzay", Date: "1998-02-18T00:00:00.000Z", Language: "French" }, { Name: "blah", Date: "1999-02-18T00:00:00.000Z", Language: "English" }],
hash = {},
result = array.filter(({ Name, Language }) => {
var key = `${Name}|${Language}`;
if (!hash[key]) return hash[key] = true;
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Using Set makes it easy to remove duplicates for as many keys as you like. I tried to be as verbose as possible so that each step was clear.
var objects = [{ "Name": "blah", "Date": "1992-02-18T00:00:00.000Z", "Language": "English", }, { "Name": "blah", "Date": "1998-02-18T00:00:00.000Z", "Language": "French", }, { "Name": "blah", "Date": "1999-02-18T00:00:00.000Z", "Language": "English" }];
function uniqueKeyVals(objects, key) {
const objVals = objects.map(object => object[key]); // ex. ["English", "French", "English"]
return objects.slice(0, new Set(objVals).size); // ex. { "English", "French" }.size = 2
}
function removeKeyDuplicates(objects, keys) {
keys.forEach(key => objects = uniqueKeyVals(objects, key));
return objects;
}
// can also use uniqueKeyVals(key) directly for just one key
console.log("Unique 'Language': \n", removeKeyDuplicates(objects, ["Language"]));
console.log("Unique ['Language', 'Name']: \n", removeKeyDuplicates(objects, ["Language", "Name"]));
I would use the underscore module for JavaScript and the unique function in this scenario. Here is a sample array of data objects:
let data = [{
name: 'blah',
date: Date.now(),
language: "en"
},
{
name: 'noblah',
date: Date.now(),
language: 'es'
},
{
name: 'blah',
date: Date.now(),
language: 'en'
}];
Then we can use the unique function in the underscore library to only return a copy of the data that has unique values associated with the language key:
const result = _.unique(data, 'language');

Javascript - Appending object to JSON File

I currently have an object:
var obj = {
username: "James",
surname: "Brandon",
id: "[2]"
}
and I want to append it to "users.json":
[
{
"username": "Andy",
"surname": "Thompson",
"id": [0],
},
{
"username": "Moe",
"surname": "Brown",
"id": [1]
}
]
Do you know how I might be able to do this?
Thanks in advance.
This answer is assuming that you are working under Node.js.
As I understand your problem you need to solve a few different programming questions.
read and write a .json file
const fs = require("fs");
let usersjson = fs.readFileSync("users.json","utf-8");
transform a json string into a javascript array
let users = JSON.parse(usersjson);
append an object to an array
users.push(obj);
transform back the array into a json string
usersjson = JSON.stringify(users);
save the json file
fs.writeFileSync("users.json",usersjson,"utf-8");
If your code is running in the browser and users.json is an output file, I guess you already have access to its content.
Use the push() method.
Also, note the missing commas in your objects.
var obj = {
username: "James",
surname: "Brandon",
id: "[2]"
};
var users = [
{
"username": "Andy",
"surname": "Thompson",
"id": [0]
},
{
"username": "Moe",
"surname": "Brown",
"id": [1]
}
];
users.push(obj);
console.log( JSON.stringify(users) );
Now that you have the updated array of objects you can upload it to the server (check this question) or offer a download to the user (check this other question).
As you have been already told, there is no way to directly update client-side a file in the server. It is also not possible to save it directly into the client filesystem.

How to parse a JSON array string in JavaScript?

I have an JSON array like this
var filter_value_data = [{"Status":[{"name":"Open","id":"1"},{"name":"Pending","id":"2"},{"name":"Resolved","id":"3"},{"name":"Closed","id":"4"},{"name":"Evaluation","id":"5"}]},{"Payment Status":[{"name":"Paid","id":"10"},{"name":"UnPaid","id":"11"},{"name":"Part Paid","id":"12"}]},{"Priority":[{"name":"Low","id":"6"},{"name":"Medium","id":"7"},{"name":"High","id":"8"},{"name":"Urgent","id":"9"}]}]
I have tried filter_value_data["Status"] which is obviously wrong. How do I get the JSON elements for Status using the names like Status,Payment Status?
filter_value_data is an array (having []), so use filter_value_data[0].Status to get the first element-object with property "Status".
It is always good to format your code in order to see the hierarchy of the structures:
var filter_value_data = [
{
"Status": [
{
"name": "Open",
"id": "1"
}, {
"name": "Pending",
"id": "2"
}, ...
]
}, {
"Payment Status": [
{
"name": "Paid",
"id": "10"
}, ...
]
}, {
"Priority": [
{
"name": "Low",
"id": "6"
}, ...
]
}
];
With your current JSON you can't get the elements with the name alone.
You can get Status with filter_value_data[0]['Status'] and Payment status with filter_value_data[1]['Payment Status'].
This is because the keys are in seperate objects in the array.
In order to get them with filter_value_data['Status'] you need to change your JSON to
var filter_value_data = {
"Status":[
{"name":"Open","id":"1"},
{"name":"Pending","id":"2"},
{"name":"Resolved","id":"3"},
{"name":"Closed","id":"4"},
{"name":"Evaluation","id":"5"}
],
"Payment Status":[
{"name":"Paid","id":"10"},
{"name":"UnPaid","id":"11"},
{"name":"Part Paid","id":"12"}
],
"Priority":[
{"name":"Low","id":"6"},
{"name":"Medium","id":"7"},
{"name":"High","id":"8"},
{"name":"Urgent","id":"9"}
]
};
I wrote this on my phone so it's not as well-formatted as usual. I'll change it ASAP.
With your current JSON, created a result which might be helpful for you.
JS:
$.each(filter_value_data,function(ind,val){
var sta = val.Status; // Status Object get displayed
for(var i=0;i<sta.length;i++){
var idVal= sta[i].id;
var nameVal = sta[i].name;
Statusarray.push(idVal,nameVal);
console.log(Statusarray);
}
})
FiddleDemo
You can use below code, it will return status object
filter_value_data[0]['Status']
filter_value_data[0]['Payment Status']
to get Single value you use :
filter_value_data[0]['Status'][0]['name']

Categories