Best way to format the JSON content in Node.js application - node.js

I am working on an NODE JS based application. Trying to figure out any easy method to get my expected result. Had tried few ways, but after reframing the JSON content not able to add the key state.
My content JSON content is in this format
[
{
"item": {
"property1": "aa",
"property2": "22"
},
"state": {
"item": {
"state": "AS",
"country": "US",
"reason": "1"
}
},
"province": {
"item": {
"name": "AS",
"method": "table",
"conf": "3"
}
}
},
...
]
Requirement is to format state as below,
{
...
"state": [
{
"item": {
"state": "AS",
"country": "US",
"reason": "1"
}
}
],
...
}
I want to format the state content. The content is expected to be an array of JSON content. After formatting state, the orginal json content need to be modified with the new content of state. The issue faced here is after formatting not able to add the key state back to the orginal JSON content.Same is the expectation for province.
Requesting support from All...Thanks in Advance....
Below is the code i had written, but the expected result is not obtained.Can anyone help me in identifying were i have gone wrong
var testJson = JSON.parse(jsonData);
var tempFinal = [];
for(let i =0; i<testJson.length; i++) {
let itemData = {};
itemData.item = testJson[i].item;
tempFinal.push(itemData);
var state = [];
state.push( testJson[i].state);
let stateData = {};
stateData.state = state;
tempFinal.push(stateData);
var service = [];
service.push( testJson[i].service);
let serviceData = {};
serviceData.service = service;
tempFinal.push(serviceData);
}
The result obtained is
[
{
"item": {
"protocol": "tcp",
"portid": "22"
}
},
{
"state": [
{
"item": {
"state": "filtered",
"reason": "no-response",
"reason_ttl": "0"
}
}
]
},
{
"service": [
{
"item": {
"name": "ssh",
"method": "table",
"conf": "3"
}
}
]
}
]
Expected is
[
{
"item": {
"a": "a",
"a": "a"
},
"state": [
{
"item": {
"c": "b",
"e": "f",
"reason_ttl": "0"
}
}
],
"service": [
{
"item": {
"name": "q",
"method": "table",
"d": "e"
}
}
]
}
]

You can try this one
//jsonData is your original json data
jsonData.map((obj1=>{
//updating state data
obj1.state=[obj1.state];
}));
//finally print it.
console.log(jsonData);

Related

Get json value based on dynamic key mapping for partial path

I am trying to get the values of a key in a json file, but there are several issues that I need to solve.
The key of the JSON is dynamic - I have another JSON in which I am given the path of the key inside the JSON.
For example, I have a json file that contains the following mapping:
{
"addressesPath":"personal.addresses"
}
This tells me that the value I am looking for is inside another key, called personal.
The JSON will look like this:
{
"username": "X1",
"id":"1X",
"type": "patron",
"group": "students",
"personal": {
"lastname": "lname",
"firstname": "fname",
"email": "test#test.test",
"phone": "1-111-111-1111",
"mobilePhone": "(111)111-1111",
"birthDate": "1979-01-23T00:00:00.000+0000",
"addresses":
{
"countryId": "US",
"addressLine1": "1111 Brannon Ford Suite 111",
"city": "Kettering",
"region": "MA",
"postalCode": "11111-1111",
"primaryAddress": true
}
}
}
So for example if the JSON is "user", what I want to get is user.personal.addresses
How can I translate "user.personal.addresses" to "users.+dynamic"?
I tried doing it just like that, but it doesn't seem to work with any type of string I extract from the mapping json file.
I have an issue because I don't know if the location I am getting is a single value or an array of values.
For example, the JSON could look like this:
{
"username": "X1",
"id":"1X",
"type": "patron",
"group": "students",
"personal": {
"lastname": "lname",
"firstname": "fname",
"email": "test#test.test",
"phone": "1-111-111-1111",
"mobilePhone": "(111)111-1111",
"birthDate": "1979-01-23T00:00:00.000+0000",
"addresses":[
{
"countryId": "US",
"addressLine1": "1111 Brannon Ford Suite 111",
"city": "Kettering",
"region": "MA",
"postalCode": "11111-1111",
"primaryAddress": true
}, {
"countryId": "US",
"addressLine1": "1112 Brannon Ford Suite 112",
"city": "Kettering",
"region": "IL",
"postalCode": "11112-1112",
"primaryAddress": false
}
]
}
}
Which means I need to determine the structure of the data I am going to get, whether it is an array or not.
Can I do this by checking if the result is a string or object? I know that arrays from JSON files are read as objects in node js.
You want something like that
With three examples
let object = {
"group": "students",
"personal": {
"addresses": {
"countryId": "US",
}
}
}
let test1 = checkObject(object, "personal.addresses")
console.log(test1);
let object2 = {
"test": {
"test_deep": [
{
"countryId": "US",
"addressLine1": "1111 Brannon Ford Suite 111"
},
{
"countryId": "US",
"addressLine1": "1112 Brannon Ford Suite 112",
}
]
}
}
let test2 = checkObject(object2, "test.test_deep")
console.log(test2);
let object3 = {
"test": {
"test_deep": "test"
}
}
let test3 = checkObject(object3, "test.test_deep")
console.log(test3);
function checkObject(object, addressesPath) {
let addres = addressesPath.split(".")
let item = object
for (let index = 0; index < addres.length; index++) {
if (typeof item[addres[index]] != 'undefined') {
item = item[addres[index]]
} else {
item = null
break
}
}
return {
type: typeof item,
is_array: Array.isArray(item),
data: item
}
}

MongoDB nested document update neither throws error nor updates document using python

I am trying to update a document in the below MongoDB collection. It neither throws an error nor updates the document.
Here is my collection:
customer_docs = [
{
"customerName": "Yeshua Galisanao",
"msgId": "100",
"productDetails": [
{
"productName": "prod1",
"prodSerialNum": "sdgha53643657354"
},
{
"productName": "prod2",
"prodSerialNum": "fafruirykjnjhgukg"
}
],
"customer-address": [
{
"primaryAddress": [
{
"street": "#43 Easy Street",
"city": "Niceton",
"state": "PH",
"zip": "57733"
}
]
},
{
"secondaryAddress": [
{
"street": "23",
"city": "seattle"
}
]
}
]
},
{
"customerName": "Karl Mike",
"msgId": "101",
"productDetails": [
{
"productName": "prod10",
"prodSerialNum": "764hreopirrrhfnsf"
},
{
"productName": "prod11",
"prodSerialNum": "fsdfhsfybdfmdsgfyuu"
}
],
"customer-address": [
{
"primaryAddress": [
{
"street": "#66 Easy Street",
"zip": "57733"
}
]
}
]
}
]
Here is the python code which tries to update serial number for the customer "Karl Mike" to "newSerailNumber":
client = pymongo.MongoClient("mongodb://127.0.0.1:27017")
db = client.MyDb
customer_col = db.customer
my_query1 = {"customerName": "Karl Mike"}
for customer in customer_col.find(my_query1):
for prod in customer["productDetails"]:
if prod["productName"] == "prod1" and prod["prodSerialNum"] != "abcdefghijklmop":
my_query2 = {
"customer": "Karl Mike",
"productDetails.productName": "prod1"
}
customer_col.update_one(my_query2, {"$set": {"productDetails.0.prodSerialNum": "newSerailNumber"}})
print("oops reached")
But the document update is not happening here. What I am doing wrong? Why the failure of document update does not throw any error?
It's my bad! First of all there is a typo in my code. Instead of using "customerName" in my_query2, I used "customer" as key.
The below code just works fine:
my_query1 = {"customerName": message["customer_name"]}
for customer in customer_col.find(my_query1):
for prod in customer["productDetails"]:
if message["prod"] == prod["productName"] and message["serial_number"] != prod["prodSerialNum"]:
my_query2 = {
"customerName": "Karl Mike",
"productDetails.productName": "prod1",
"productDetails.prodSerialNum": prod["prodSerialNum"]
}
customer_col.update_many(my_query2, {"$set": {"productDetails.$.prodSerialNum": "newSerailNumber"}})
print("oops reached")
But still wondering - why there was no error thrown for the same.

Node.js | Remove element in json

I have a json like this:
var myjson = [
{
"id": "1"
},
{
"id": "2"
},
{
"id": "3"
},
{
"id": "4"
},
{
"id": "5"
}
];
I want the incoming id removed from myjson when app.delete() is triggered.
Forexample incoming id = 3. Then myjson's new look:
var myjson = [
{
"id": "1"
},
{
"id": "2"
},
{
"id": "4"
},
{
"id": "5"
}
];
You can use Array.prototype.filter() to do this like the code below:
const removeItem = (id) => myjson.filter(item => item !== id);

Add response to each item for loop in node.js and postgres

I have an array of schools like this:
{
"schools": [
{
"name": "S1",
"id": 1
},
{
"name": "S2",
"id": 2
},
{
"name": "S3",
"id": 3
}
]
}
and each school has schedule. To Get that I iterate the schools array in a promise and when I get the response I get an array like this
{
"schools": [
{
"name": "S1",
"id": 1
},
{
"name": "S2",
"id": 2
},
{
"name": "S3",
"id": 3
}
],
"schedules": [
[],
[
{
"id_schedule": 58,
"hour1": "13:00:00",
"hour2": "20:00:00",
"id_schools_schedule": 2
}
],
[
{
"id_schedule": 59,
"hour1": "06:30:00",
"hour2": "22:30:00",
"id_schools_schedule": 3
}
]
]
}
I want to know. how to asign the response of each item?
this is my code
for (var i =0; i < datosRes.schools.length; i++){
array_horarios.push(ObtSchedule(datosRes.schools, i))
}
Promise.all(array_horarios).then(response => {
datosRes.horarios = response;
eq.local = data;
}).catch(err => {
return res.json(200,{"datos":datosRes});
})
function ObtHorario(schools, i){
return new Promise(function(resolve, reject){
var id_school = schools[i].id;
Mod_Schedule.obtSchedule(id_school,function(error, data){
if(error || data.error){
errorDB = {"error_log": error, "error_data": data.error};
reject(errorDB)
}else{
resolve(data)
}
})
})
}
What I am doing wrong?
I get the response but only I want to add to each item of schools the schedules
Thanks in advance
First thing first:
You can send ONE response to ONE request. So your question to send multiple responses is invalid.
Here's what you can do, you can get the array of schools with their schedules.
If you are using MongoDB, here's what you can do:
Using Aggregate query:
db.schools.aggregate([
{
$match: {} // Your condition to match schools here
},
{
$lookup: {
from:"schedules",
localField: id,
foreignField: id_schools_schedule,
as: "schedulesData"
}
},
]);
Here, you will get data something like:
[
{
"name": "S1",
"id": 1,
"schedulesData": []
},
{
"name": "S2",
"id": 2,
"schedulesData": [{
"id_schedule": 58,
"hour1": "13:00:00",
"hour2": "20:00:00",
"id_schools_schedule": 2
}]
},
{
"name": "S3",
"id": 3,
"schedulesData": [
{
"id_schedule": 59,
"hour1": "06:30:00",
"hour2": "22:30:00",
"id_schools_schedule": 3
}
]
}
]

How to get filtered result by using Hash Index in ArangoDB?

My data:
{
"rootElement": {
"names": {
"name": [
"Haseb",
"Anil",
"Ajinkya",
{
"city": "mumbai",
"state": "maharashtra",
"job": {
"second": "bosch",
"first": "infosys"
}
}
]
},
"places": {
"place": {
"origin": "INDIA",
"current": "GERMANY"
}
}
}
}
I created a hash index on job field with the API:
http://localhost:8529/_db/_api/index?collection=Metadata
{
"type": "hash",
"fields": [
"rootElement.names.name[*].jobs"
]
}
And I make the search query with the API:
http://localhost:8529/_db/_api/simple/by-example
{
"collection": "Metadata",
"example": {
"rootElement.names.name[*].jobs ": "bosch"
}
}
Ideally, only the document containing job : bosch should be returned as a result. But for me it gives all the documents in the array name[*]. Where I am doing mistake?
Array asterisk operators are not supported by simple queries.
You need to use AQL for this:
FOR elem IN Metadata FILTER elem.rootElement.names.name[*].jobs = "bosch" RETURN elem
You can also execute AQL via the REST interface - However you should rather try to let a driver do the heavy lifting for you.

Resources