Adding data to JSON array - javascript

I have a JSON Array inside my Node.js code with the following schema:
{
"status": "ok",
"data": [
{
"id": 1,
"active": true,
"createdAt": "2017-07-21T15:39:31.000Z",
"updatedAt": "2017-07-21T15:47:13.000Z"
}
]
}
and I want to add data so it will look like:
{
"status": "ok",
"data": [
{
"id": 1,
"active": true,
"createdAt": "2017-07-21T15:39:31.000Z",
"updatedAt": "2017-07-21T15:47:13.000Z",
"information": "someInformation"
}
]
}
Can you help me how to do this?
Thanks!

Like this? access the data property, of the obj variable, and the first element in that array, then set a new property on that object equal to your string.
var obj = {
"status": "ok",
"data": [
{
"id": 1,
"active": true,
"createdAt": "2017-07-21T15:39:31.000Z",
"updatedAt": "2017-07-21T15:47:13.000Z"
}
]
};
obj.data[0].information = "someInformation";
console.log( obj );

Since you have already the JSON you should firstly parse it, because JSON is a string. After parsing you will get object that should be saved in some variable, then you can access it as general object and add the property you want. Then you have to transform it to JSON string again. It will be like this
var parsed = JSON.parse(data); // Now we are transforming JSON string into the object
//Now you may do whatever you want
parsed.newprop = 'some text';
parsed.hello = 'Hellow world';
data = JSON.stringify(parsed); // Now we are replacing the previous version of JSON string to new version with additional properties

var dataContainer = {
"status": "ok",
"data": [
{
"id": 1,
"active": true,
"createdAt": "2017-07-21T15:39:31.000Z",
"updatedAt": "2017-07-21T15:47:13.000Z"
}
]
};
for(var i = 0; i < dataContainer.data.length; i++) {
dataContainer['data'][i]['information'] = "some information";
}
Hope it helps you !

Related

is it possible to retrieve and print the data from a json object inside json array without using any index values and specific keys

[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
now i need to check and print the JSON Object inside the JSON Array if category is present then it should print and in future if category is changed according to that if we pass parameter the output should print we don't hard code the code
i have tried by using key values it is coming but if the key value changes it is not printing the object
EX:-
[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
in the above code i have printed category object but if category changed to categories it is not printing so i want a code which can read the code and based on parameters user giving it should be print the output
Try this.
For Example:
let a = [{"id": "628ba44f5a6de600071d16fa","category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}]}]
function print (values){return (a[0][`${values}`])}
//now just pass any name like "category" or in future "categories"
print("category") //this will retrun the array.
Now modify with your requirements.
It seems you want to get the value of the key(that can be parameterized).
const jsonArray = [
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}
]
}
];
const parameter = "category";
const result = jsonArray.find(({ [parameter]: value }) => value);
if (result) {
console.log(result);
} else {
console.log(`No object found with ${parameter}`);
}
If this is not what you are looking for, then please add your code snippet for better understanding.

Parsing nested JSON using JSON Schema or Classes

I have a large nested JSON response in following sample format:
{
"type": "folder",
"path": "Path1",
"owner": "user1",
"entries": [{
"type": "folder",
"path": "Path2",
"owner": "user1",
"entries": [{
"type": "folder",
"path": "Path3",
"owner": "user1"
},
{
"type": "file",
"path": "FullFilePath1",
"owner": "user1"
}
]
}]
}
I wanted to extract all the file type with selected keys and also add additional keys:
{
"type": "file",
"path": "FullFilePath1",
"Application": "My Application",
"UpdatedTime": "Time"
}
I am using nodejs. I need inputs in parsing the JSON file in best way. I was trying to check if I can use JSON Schema and Classes to do this but still didnt get through.
Could you please guide me?
Since you are dealing with JSON, you can simply load it into a JavaScript variable using require:
let data = require('./data.json');
You can then loop the variable for all entries tag
let fileData = require('./data.json');
let allEntries = [];
loadEntries(fileData);
function loadEntries(data) {
if(data.entries) {
for (let index = 0; index < data.entries.length; index++) {
const entry = data.entries[index];
// Do something with the entry
allEntries.push(entry);
loadEntries(entry);
}
}
}

Find and replace key in Javascript object

I'm accessing a JSON that comes back looking like this:
[
{
"itemType": "SelectionTitle",
"name": "1105F.MID",
"active": true,
"isFactoryDefault": false,
"factoryCode": "",
"seasons": [],
"denominations": [],
"groups": [],
"length": 0,
"_id": "5ada2217c114ca048e1db9b0",
"created_by": "5ab57289d8d00507b29a3fdd",
"selectionFile": {
"itemType": "SelectionFile",
"name": "1105F.MID",
"active": true,
"isFactoryDefault": false,
"selectionType": "Music",
"sfzFile": "",
"destination": "/data/uploads",
"encoding": "7bit",
"fieldname": "file",
"filename": "782f49a7cd72b865b4e2d286816792e7",
...
"found": true,
"flError": false,
"error_strings": [],
"_id": "5ada2217c114ca048e1db9af",
"created_by": "5ab57289d8d00507b29a3fdd",
"slug": "1105fmid",
"__v": 0,
"createdAt": "2018-04-20T17:23:35.216Z",
"updatedAt": "2018-04-20T17:23:35.788Z",
"selectionTitles": null,
"id": "5ada2217c114ca048e1db9af"
},
"slug": "1105fmid",
"createdAt": "2018-04-20T17:23:35.285Z",
"updatedAt": "2018-04-20T17:23:35.285Z",
"__v": 0,
"id": "5ada2217c114ca048e1db9b0"
}, ...
The react-select node module that I am using takes the key "label" to generate a populated dropdown.
The JSON is coming from the web so I can't control how the JSON is setup. How do I parse the JSON to find all the instances of "name" and replace that key with "label" ?
For example "name" : 1105F.MID" should be changed to "label" : "1105.MID"
Would it be inefficient to convert the entire thing to a string and use the javascript method find/replace?
Assuming your JSON array is stored in the variable data:
data.forEach(item => item.label = item.name)
This would be sufficient to duplicate the name property as the label property for each item in the array.
I have created a function replace() to deal with every object and nested objects, which will add property 'label' if 'name' property is found. Pls see if it's useful to you.
var arr = [
{
"itemType": "SelectionTitle",
"name": "1105F.MID",
"active": true,
"isFactoryDefault": false,
"factoryCode": "",
"seasons": [],
"denominations": [],
"groups": [],
"length": 0,
"_id": "5ada2217c114ca048e1db9b0",
"created_by": "5ab57289d8d00507b29a3fdd",
"selectionFile": {
"itemType": "SelectionFile",
"name": "1105F.MID"
}
},
{
"itemType": "SelectionTitle",
"name": "test",
"active": true,
"isFactoryDefault": false,
"factoryCode": "",
"seasons": [],
"denominations": [],
"groups": [],
"length": 0,
"_id": "5ada2217c114ca048e1db9b0",
"created_by": "5ab57289d8d00507b29a3fdd",
"selectionFile": {
"itemType": "SelectionFile",
"name": "testing"
}
}
]
// this method will take care of adding new property
function replace(obj, from, to) {
Object.entries(obj).forEach(([key, value]) => (
key == from && (obj[to] = obj[from])
, typeof value === "object" && replace(value, from, to)
))
}
arr.forEach(d => replace(d, 'name', 'label'))
// you can check this log for property 'label' whereever 'name' exists
console.log(arr)
Relying on the structure of server response is bad; especially when you say you have not control over it. A better way would be to always parse the server response, construct whatever necessary for the react-select component to work and pass that only.

Print contents of JSON Object

I have an object in which I used JSON Stringify with to view its contents like so:
var testing = JSON.stringify($scope.test, null, 4);
And the object looks like this when i do console.log(testing):
{
"_id": "53e866a8a595b7041f9510c9",
"start": "2014-08-04T07:00:00.000Z",
"end": "2014-08-16T07:00:00.000Z",
"location": "Australia",
"name": "Joe's Surprise",
"__v": 1,
"array": [
{
"_id": "53ddc8c98ae4813c0420e189",
"provider": "local",
"name": "Test User",
"username": "testUser",
"email": "test#test.com",
"hashedPassword": "e5ri7OVhzNQMZpSqxnB3p2FyrpxskFE3yM8jHn5hfzZZvdd57YhhJrjFWJqBQhhyZz6y8UG68mr+rQ95admtfw==",
"salt": "PVEFtMfyJ/7TX9Do0cYMdQ==",
"__v": 2,
"attending": [
"53e866a8a595b7041f9510c9"
],
"role": "user"
},
]
}
however, I want to print out the username attribute within the array attribute of variable testing but I am unable to do so. I've tried doing a for loop like so:
for(var i = 0; i < testing.array.length; i++){
console.log(testing.array[i].username);
}
But the .length attribute is considered undefined. I've also tried simply doing console.log(testing._id) to see if that works but this returns undefined. I'm not sure what I'm doing wrong, can anyone help? Thanks!
var testing = JSON.stringify($scope.test, null, 4);
is converting $scope.test into a string (presumably so you can view in a human readible format). A string contains no arrays or properties. You want it in its original form, not in a string.
you probably want:
for(var i = 0; i < $scope.test.array.length; i++){
console.log($scope.test.array[i].username);
}

how can I put in HTML certain information form my json

I am having problem with my data.
My JSon looks like that:
[
{
"link": {
"created_at": "2013-10-07T13:31:43+09:00",
"id": 8,
"items_count": 4,
"key": "0iqVSnTU-BtJ1ItVKRe2VMWvRMU",
"mode": "standard",
"name": "sdasadads",
"pusher_key": "1jtsrzl3n6i1DKA3tSZJM6LPnfQ",
"readonly_key": "R_dD5oHMsruu0YzYVKEOA8hKKXA-r",
"updated_at": "2013-10-08T14:06:07+09:00",
"user_id": 2
}
},
{
"link": {
"created_at": "2013-10-07T13:32:56+09:00",
"id": 9,
"items_count": 1,
"key": "Mj-6Cc-_qaGlVTPgqKexzeijYNA",
"mode": "standard",
"name": "Untitled2",
"pusher_key": "hGE0D8TSar_H_Gv9MWdpj26gamM",
"readonly_key": "T53SNKPgyf7KvRUMzDQPaM99AAc-r",
"updated_at": "2013-10-07T13:33:14+09:00",
"user_id": 2
}
},
{
"link": {
"created_at": "2013-10-11T11:18:06+09:00",
"id": 10,
"items_count": 0,
"key": "X_ZoKxFPHtsvSU5W11gXx1653FU",
"mode": "standard",
"name": "Usdadasas",
"pusher_key": "0PZ860awofRKB9XIrXba-xY6u14",
"readonly_key": "2rzrRZAaR7UZRK3UbUId8xmFzd4-r",
"updated_at": "2013-10-11T11:18:06+09:00",
"user_id": 2
}
}
}
I am trying to print put all the names of the links like that:
$.post( "http://0.0.0.0:9292/api/links", function( data ) {
document.getElementById("test").innerHTML = data[link][0].name;
});
but it doesn't work.
How can I grub all the names and put it in html?
The objects are inside the array, not the other way around.
link is a literal property name, not a variable containing one as a string
Thus:
data[0]['link']['name']
You'll also need to make sure that the response has an application/json content type.
Grabbing all the names will require you to use a loop and change the 0 each time round it.
First of all change last "}" to "]" (your top structure is array not object )
Then try this
$.post( "http://0.0.0.0:9292/api/links", function( data ) {
document.getElementById("test").innerHTML = data[0].link.name;
});
Array.prototype.map() is a good way to fetch something from data structure. With your test data in data variable, could would look like this:
Example here.
<div class="names"></div>
var names = data.map(function (item) {
return item.link.name
});
document.querySelector(".names").innerHTML = names;

Categories