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));
Hello I have json file:
var jsonData = {
"name": "James",
"age": 22,
"nodes": [
{
"name": "John",
"age": 24,
"nodes": [
{
"name": "Jack",
"age": 65,
"nodes": [
{
"name": "Harry",
"age": 70,
"nodes": []
}
]
},
{
"name": "Joe",
"age": 10,
"nodes": []
}
]
},
{
"name": "Daniel",
"age": 30,
"nodes": []
}
]
}
I need a function that returns output like this:
James 22
James - John 24
James - John - Jack 65
James - John - Jack - Harry 70
James - John - Joe 10
James - Daniel 30
I tried to use recursive function but I don't know how to return output like this one and return age only on last child..
Code:
var json = jsonData;
var prev = [];
function sortData(obj, prev) {
var i = 0;
prev.push(obj.name + " " + obj.age);
console.log(prev);
if (obj.nodes.length > 0) {
while (i < obj.nodes.length) {
sortData(obj.nodes[i], prev);
i++;
prev.pop();
}
}
}
sortData(json, prev);
My function returns output in multiple arrays, so I don't know how to operate with that to return output like that. Will be grateful for any help. Thanks!
You might consider just passing around strings representing the current property path recursively, that way you can just concatenate and pass the value around without worrying about it being mutated. Also, it'll be a lot easier to use array methods like forEach than to use an i variable and manually iterate:
var jsonData={"name":"James","age":22,"nodes":[{"name":"John","age":24,"nodes":[{"name":"Jack","age":65,"nodes":[{"name":"Harry","age":70,"nodes":[]}]},{"name":"Joe","age":10,"nodes":[]}]},{"name":"Daniel","age":30,"nodes":[]}]}
function getAge({ name, age, nodes }, oldPropStr = '') {
const propStr = (oldPropStr ? oldPropStr + ' - ' : '') + name;
console.log(propStr + ' ' + age);
nodes.forEach(node => getAge(node, propStr));
}
getAge(jsonData);
Also, you might note that the current variable name of jsonData is misleading. There's no such thing as a "JSON Object". If you have an object or array, then you have an object or array, full stop. JSON format is a method of representing an object in a string, like const myJSON = '{"foo":"bar"}'. If there are no strings, serialization, or deserialization involved, then JSON is not involved either. Maybe call the variable people or something instead?
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.
If I have a JSON Object Map :
var dataItem=[{
"Lucy":{
"id": 456,
"full_name": "GOOBER, ANGELA",
"user_id": "2733245678",
"stin": "2733212346"
},
"Myra":{
"id": 123,
"full_name": "BOB, STEVE",
"user_id": "abc213",
"stin": "9040923411"
}
}]
I want to iterate through this list and access the names (i.e. Lucy, Myra ) and corresponding information
All the loops that I came across looped through the list like this :
var dataItem = [
{"Name":"Nthal","Class":3,"SubjectName":"English "},
{"Name":"Mishal","Class":4,"SubjectName":"Grammer"},
{"Name":"Sanjeev","Class":3,"SubjectName":"Social"},
{"Name":"Michal","Class":5,"SubjectName":"Gk"},
]
for(x in dataItem)
{
alert(dataItem[x].Name);
alert(dataItem[x].Class);
alert(dataItem[x].SubjectName);
}
Thanks in advance
What you have there is not JSON, maybe because you've already parsed it. You have is an array consisting of a single object, with names for its keys. Regardless, I'll show you how to access that data:
var data = dataItem[0];
for(name in data) {
alert(name);
alert(data[name].id);
alert(data[name].full_name);
}
for (var x in dataItem[0]) {
if (dataItem[0].hasOwnProperty(x)) {
console.log(x);
}
}
http://jsfiddle.net/B44LW/
If you want other properties, then you can use the bracket notation:
dataItem[0][x].id
I want to remove JSON element or one whole row from JSON.
I have following JSON string:
{
"result":[
{
"FirstName": "Test1",
"LastName": "User",
},
{
"FirstName": "user",
"LastName": "user",
},
{
"FirstName": "Ropbert",
"LastName": "Jones",
},
{
"FirstName": "hitesh",
"LastName": "prajapti",
}
]
}
var json = { ... };
var key = "foo";
delete json[key]; // Removes json.foo from the dictionary.
You can use splice to remove elements from an array.
Do NOT have trailing commas in your OBJECT (JSON is a string notation)
UPDATE: you need to use array.splice and not delete if you want to remove items from the array in the object. Alternatively filter the array for undefined after removing
var data = {
"result": [{
"FirstName": "Test1",
"LastName": "User"
}, {
"FirstName": "user",
"LastName": "user"
}]
}
console.log(data.result);
console.log("------------ deleting -------------");
delete data.result[1];
console.log(data.result); // note the "undefined" in the array.
data = {
"result": [{
"FirstName": "Test1",
"LastName": "User"
}, {
"FirstName": "user",
"LastName": "user"
}]
}
console.log(data.result);
console.log("------------ slicing -------------");
var deletedItem = data.result.splice(1,1);
console.log(data.result); // here no problem with undefined.
You can try to delete the JSON as follows:
var bleh = {first: '1', second: '2', third:'3'}
alert(bleh.first);
delete bleh.first;
alert(bleh.first);
Alternatively, you can also pass in the index to delete an attribute:
delete bleh[1];
However, to understand some of the repercussions of using deletes, have a look here
For those of you who came here looking for how to remove an object from an array based on object value:
let users = [{name: "Ben"},{name: "Tim"},{name: "Harry"}];
let usersWithoutTim = users.filter(user => user.name !== "Tim");
// The old fashioned way:
for (let [i, user] of users.entries()) {
if (user.name === "Tim") {
users.splice(i, 1); // Tim is now removed from "users"
}
}
Note: These functions will remove all users named Tim from the array.
I recommend splice method to remove an object from JSON objects array.
jQuery(json).each(function (index){
if(json[index].FirstName == "Test1"){
json.splice(index,1); // This will remove the object that first name equals to Test1
return false; // This will stop the execution of jQuery each loop.
}
});
I use this because when I use delete method, I get null object after I do JSON.stringify(json)
All the answers are great, and it will do what you ask it too, but I believe the best way to delete this, and the best way for the garbage collector (if you are running node.js) is like this:
var json = { <your_imported_json_here> };
var key = "somekey";
json[key] = null;
delete json[key];
This way the garbage collector for node.js will know that json['somekey'] is no longer required, and will delete it.
Fix the errors in the JSON: http://jsonlint.com/
Parse the JSON (since you have tagged the question with JavaScript, use json2.js)
Delete the property from the object you created
Stringify the object back to JSON.
As described by #mplungjan, I though it was right. Then right away I click the up rate button. But by following it, I finally got an error.
<script>
var data = {"result":[
{"FirstName":"Test1","LastName":"User","Email":"test#test.com","City":"ahmedabad","State":"sk","Country":"canada","Status":"False","iUserID":"23"},
{"FirstName":"user","LastName":"user","Email":"u#u.com","City":"ahmedabad","State":"Gujarat","Country":"India","Status":"True","iUserID":"41"},
{"FirstName":"Ropbert","LastName":"Jones","Email":"Robert#gmail.com","City":"NewYork","State":"gfg","Country":"fgdfgdfg","Status":"True","iUserID":"48"},
{"FirstName":"hitesh","LastName":"prajapti","Email":"h.prajapati#zzz.com","City":"","State":"","Country":"","Status":"True","iUserID":"78"}
]
}
alert(data.result)
delete data.result[3]
alert(data.result)
</script>
Delete is just remove the data, but the 'place' is still there as undefined.
I did this and it works like a charm :
data.result.splice(2,1);
meaning : delete 1 item at position 3 ( because array is counted form 0, then item at no 3 is counted as no 2 )
Try this following
var myJSONObject ={"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
console.log(myJSONObject);
console.log(myJSONObject.ircEvent);
delete myJSONObject.ircEvent
delete myJSONObject.regex
console.log(myJSONObject);
if we want to remove one attribute say "firstName" from the array
we can use map function along with delete as mentioned above
var result= [
{
"FirstName": "Test1",
"LastName": "User",
},
{
"FirstName": "user",
"LastName": "user",
},
{
"FirstName": "Ropbert",
"LastName": "Jones",
},
{
"FirstName": "hitesh",
"LastName": "prajapti",
}
]
result.map( el=>{
delete el["FirstName"]
})
console.log("OUT",result)
Could you possibly use filter? Say you wanted to remove all instances of Ropbert
let result = [
{
"FirstName": "Test1",
"LastName": "User",
},
{
"FirstName": "user",
"LastName": "user",
},
{
"FirstName": "Ropbert",
"LastName": "Jones",
},
{
"FirstName": "hitesh",
"LastName": "prajapti",
}
]
result = result.filter(val => val.FirstName !== "Ropbert")
(result now contains)
[
{
"FirstName": "Test1",
"LastName": "User",
},
{
"FirstName": "user",
"LastName": "user",
},
{
"FirstName": "hitesh",
"LastName": "prajapti",
}
]
You can add further values to narrow down the items you remove, for example if you want to remove on first and last name then you could do this:
result = result.filter(val => !(val.FirstName === "Ropbert" && val.LastName === "Jones"))
Although as noted, if you have 4 'Ropbert Jones' in your array, all 4 instances would be removed.
try this
json = $.grep(newcurrPayment.paymentTypeInsert, function (el, idx) { return el.FirstName == "Test1" }, true)
A descent Solution is here
My JSON array is
const [myData, setData] = useState([{username:'faisalamin', share:20}, {username:'john', share:80}])
I want to delete john on a button click in renderItem or in .map
const _deleteItem = (item) => {
const newData = myData.filter(value => { return value.username !== item.username });
setData(newData);
}