Modify existing json file using nodejs - javascript

I have a json file named a1.json->(It has the following structure)
{ "Key1" :
[ {
"Key11" : "Value11" ,
"Key12" : "Value12"
},
{
"Key21" : "Value21" ,
"Key22" : "Value22"
}
]
}
I am iterating through a data file which has certain values. If the values match i will have to add an extra key to that particular dictionary only. For example-
{ "Key1" :
[ {
"a" : "A1" ,
"b" : "B1"
},
{
"a" : "A2" ,
"b" : "B2"
}
]
}
I want to add a key value pair in that list whose key value "a" is "A1". So the final result will look something like this-
{ "Key1" :
[ {
"a" : "A1" ,
"b" : "B1" ,
"New_Key_Array" :
[
{
"Found" : "yes",
"Correctness" : "true"
}
]
},
{
"a" : "A2" ,
"b" : "B2"
}
]
}
How do I go about this. I am a bit new to JSON formatting and still learning how to edit existing JSON files?

You can use JSON.parse() to parse your json file/string into a JavaScript object. In your example:
let j = JSON.parse('{ "Key1" :[ { "a" : "A1" , "b" : "B1"},{"a" : "A2" , "b" : "B2"}]}');
To add a new key to your object, it's possible with native JavaScript code, if that's what you want:
j.Key1[0]["New_Key_Array"] = [ { Found: "yes", Correctness: "true" } ];
To convert back into json formatted string, you can use the JSON.stringify() function.

I am providing a code snippet for your problem:
let j = JSON.parse('{ "Key1" :[ { "a" : "A1" , "b" : "B1"},{"a" : "A2" , "b" : "B2"}]}');
console.log("JSON at the beginning:\n", j);
j.Key1.forEach((element, index) =>{
if(element.a === "A1"){
//Here I have to edit the JSON obj
j.Key1[index]["New_Key_Array"] = [ { Found: "yes", Correctness: "true" } ];
}
});
console.log("JSON edited:\n ",j);
let objString =JSON.stringify(j);

Related

array in array filter - javascript

hello i need help with array , as you can see my data
{
"age" : "18",
"altKategoriler" : [ "Dramalar" ],
"category" : [ "Aksiyon", "Heyecanlı", "Gerilim" ],
"id" : 5240718100,
"img" : "https://i.ibb.co/k8wx5C8/AAAABW9-ZJQOg-MRljz-Zwe30-JZw-Hf4vq-ERHq6-HMva5-ODHln-Ci-OEV6ir-Rcjt88tcnm-QGQCKpr-K9h-Oll-Ln-Sbb-EI.jpg",
"izlenilmeSayisi" : 0,
"logo" : "https://i.ibb.co/Rb2SrcB/AAAABfcrhh-Rni-Ok-Ct2l-Rys-ZYk-Oi-T0-XTeagkrw-Mkm-U0h-Lr-WIQZHEHg-VXihf-OWCwz-Vv-Qd7u-Ffn-DFZEX2-Ob.webp",
"oyuncuKadrosu" : [ "Diego Luna", "Michael Pena", "Scoot McNairy", "Tenoch Huerta", "Joaquin Cosio" ],
"senarist" : [ "Doug Miro" ],
"time" : "3 Sezon",
"title" : "Narcos: Mexico",
"type" : "Dizi",
"videoDescription" : "Guadalajara Karteli'nin yükselişinin gerçek öyküsünü anlatan bu yeni ve cesur Narcos hikâyesinde, Meksika'daki uyuşturucu savaşının 1980'lerdeki doğuşuna tanıklık edin.",
"videoQuality" : "HD",
"videosrc" : "https://tr.vid.web.acsta.net/uk/medias/nmedia/90/18/10/18/19/19550785_hd_013.mp4",
"year" : "2021",
"yonetmen" : [ "Carlo Bernard", "Chris Brancato" ]
}
I can access elements such as id , title or logo because they are not arrays.
How can I loop through the data inside the array since there is an array in the category in yield?
var data = this.database.filter((item) => item.type == searchType)
var data = this.database.filter((item) => item.category == searchCategory)
It's okay because my type value doesn't have an array.
But when I enter my category value, it only gets the first index[0]. It does not look at other indexes.
in summary,
item.category[0] , item.category[1] , item.category[2]...........
How can I get index browsing like
if your data looks like this :
let data ={
"age" : "18",
"altKategoriler" : [ "Dramalar" ],
"category" : [ "Aksiyon", "Heyecanlı", "Gerilim" ],
"id" : 5240718100,
"img" : "https://i.ibb.co/k8wx5C8/AAAABW9-ZJQOg-MRljz-Zwe30-JZw-Hf4vq-ERHq6-HMva5-ODHln-Ci-OEV6ir-Rcjt88tcnm-QGQCKpr-K9h-Oll-Ln-Sbb-EI.jpg",
"izlenilmeSayisi" : 0,
"logo" : "https://i.ibb.co/Rb2SrcB/AAAABfcrhh-Rni-Ok-Ct2l-Rys-ZYk-Oi-T0-XTeagkrw-Mkm-U0h-Lr-WIQZHEHg-VXihf-OWCwz-Vv-Qd7u-Ffn-DFZEX2-Ob.webp",
"oyuncuKadrosu" : [ "Diego Luna", "Michael Pena", "Scoot McNairy", "Tenoch Huerta", "Joaquin Cosio" ],
"senarist" : [ "Doug Miro" ],
"time" : "3 Sezon",
"title" : "Narcos: Mexico",
"type" : "Dizi",
"videoDescription" : "Guadalajara Karteli'nin yükselişinin gerçek öyküsünü anlatan bu yeni ve cesur Narcos hikâyesinde, Meksika'daki uyuşturucu savaşının 1980'lerdeki doğuşuna tanıklık edin.",
"videoQuality" : "HD",
"videosrc" : "https://tr.vid.web.acsta.net/uk/medias/nmedia/90/18/10/18/19/19550785_hd_013.mp4",
"year" : "2021",
"yonetmen" : [ "Carlo Bernard", "Chris Brancato" ]
}
and if we have array of data you can do something like this :
myArray.filter(item=>item.category.indexOf(searchCategory)>=0)
but if you want to explore in object rather than array you can do this :
data.category.indexOf(searchCategory)>=0
You could make this a bit generic, by testing whether the targeted field is an array, using Array.isArray, and then call a filter on each element, and see if any is positive (using .some()). The filter can be function that is provided, so that it can perform a simple match, or apply a regular expression, or anything else.
Instead of testing with Array.isArray you could skip that step and check whether the value has a .some() method. If so, calling it will give the desired outcome, and otherwise (using the .? and ?? operators), the filter should be applied to the value as a whole:
Here is how that looks:
function applyFilter(data, field, filter) {
return data.filter(item => item[field]?.some(filter) ?? filter(item));
}
// Example use:
var data = [{
"category" : [ "Action", "Thriller", "Horror"],
"type" : "Series",
}, {
"category" : [ "Historical", "Romance" ],
"type" : "Theatre",
}];
// Find entries that have a category that looks like "roman*":
var result = applyFilter(data, "category", value => /^roman.*/i.test(value));
console.log(result);
If you are running on an older version of JavaScript, and don't have support for .? or ??, then use:
return data.filter(item => Array.isArray(item[field])
? item[field].some(filter)
: filter(item));

add to my nested json doesn't work correctly

I am trying to "ADD" a new key "resource1" to my below JSON.
I tried jsonFile["entry"][2] = "resource1" . This worked.
Now i want to add an object with "resourceType", "code", "subject"...... like how it is displayed for "resource" in my json below. How do i achieve this???
Like this --> jsonFile["entry"][2]["resource1"] = {"resourceType" : "Observation"} ?????
Need help here
jsonFile:
{
"resourceType" : "Bundle",
"type" : "transaction",
"entry" : [
{
"fullUrl": "urn:uuid:patient",
"resource" : {
"resourceType" : "Patient",
"name" : [
{
"given": ["Lola"],
"family": "Tes"
}
]
},
"request" : {
"method" : "POST",
"url" : "Patient"
}
},
{
"resource" : {
"resourceType" : "Observation",
"code" : {
"coding" : [
{
"system": "http://loinc.org",
"code": "15074-8",
"display": "Glucose [Moles/volume] in Blood"
}
]
},
"subject": {
"type" : "Patient",
"reference" : "urn:uuid:patient"
},
"valueQuantity": {
"value": "5",
"unit": "mmol/l",
"system": "http://unitofmeasure.org",
"code": "mmol/L"
}
},
"request" : {
"method" : "POST"
}
}
]
}
Looks like you are trying to add the property to non existing object.
From your example.
jsonFile["entry"][2] = "resource1"
this worked because you are adding this to existing property(i.e. jsonFile has entry object which is array. So, it's just simply pushing this to array.
But when you are trying this,
jsonFile["entry"][2]["resource1"] = {"resourceType" : "Observation"}
it's trying to add property to non extsting object(i.e. jsonFile has entry, but entry has only 0 and 1 position objects in array. So, this will throw error.
To add property at 2nd position, you need to initialise object at that position and then you can add property.
You can do it in following ways,
jsonFile["entry"][2] = {}
jsonFile["entry"][2]["resource1"] = {"resourceType" : "Observation"}
Or
jsonFile["entry"][2] = {"resource1":{"resourceType" : "Observation"}}
You can add property to object if and only if that object is exists.

Find nested property from ember lodash and pick the value

I am new to javascript.
I would like to check whether the specific nested property is present or not in an array of items, ex)
[{
"_id" : ObjectId("5c4ec057e21b840001968d31"),
"status" : "ACTIVE",
"customerId" : "sample-book",
"bookInfo" : {
"bookChunks" : [
{
"key" : "Name",
"value" : "test"
},
{
"key" : "Surname1",
"value" : "testtt"
},
{
"key" : "user-contact",
"value" : "sample-value",
"ContactList" : {
"id" : "sample-id",
"timeStamp" : "Tue, 20 Sep 2016 07:49:25 +0000",
"contacts" : [
{
"id" : "contact-id1",
"name" : "Max Muller",
"phone_number" : "+XXXXXXX"
},
{
"id" : "contact-id2",
"name" : "Max Muller",
"phone_number" : "+XXXXXXX"
}
]
}
}
]
}
},
{
"_id" : ObjectId("5c4ec057e21b840001968d32"),
"status" : "ACTIVE",
"customerId" : "sample-book1",
"bookInfo" : {
"bookChunks" : [
{
"key" : "Name",
"value" : "test"
},
{
"key" : "Surname1",
"value" : "testtt"
}
]
}
}]
Here, I would like to find whether any item has ContactList or contacts present. If it is present take the item and put it in a separate list.
I am using ember-lodash. Using normal javascript or lodash would be fine for me. Any help will be really appreciated.
You could use filter and some. This returns all the objects which have at least one object with ContactList property inside bookInfo.bookChunks array.
const input=[{"_id":"5c4ec057e21b840001968d31","status":"ACTIVE","customerId":"sample-book","bookInfo":{"bookChunks":[{"key":"Name","value":"test"},{"key":"Surname1","value":"testtt"},{"key":"user-contact","value":"sample-value","ContactList":{"id":"sample-id","timeStamp":"Tue, 20 Sep 2016 07:49:25 +0000","contacts":[{"id":"contact-id1","name":"Max Muller","phone_number":"+XXXXXXX"},{"id":"contact-id2","name":"Max Muller","phone_number":"+XXXXXXX"}]}}]}},{"_id":"5c4ec057e21b840001968d32","status":"ACTIVE","customerId":"sample-book1","bookInfo":{"bookChunks":[{"key":"Name","value":"test"},{"key":"Surname1","value":"testtt"}]}}]
const output = input.filter(o =>
o.bookInfo.bookChunks.some(c => "ContactList" in c)
)
console.log(output)
If you just want to check if any of the objects have ContactList, you could replace filter with another some
(Note: This assumes that bookInfo.bookChunks will not be undefined. Otherwise you'd have to add a undefined check before using the nested property)

Papaparse output without comma (multiple records)

I have CSV that is parsed with Papaparse and the output is the following:
[
{
"id" : 1,
"title" : "Test1"
},
{
"id" : 2,
"title" : "Test2"
}
]
And I need to receive the following instead:
[ //also could be without this
{
"id" : 1,
"title" : "Test1"
} //without the comma
{
"id" : 2,
"title" : "Test2"
}
] //also could be without this
Is there a way to directly remove that comma that separates two records with Papaparse or do I have to do it through code?
Thanks.

If condition does not work / not running

I'm trying to match mongodb object id with if condition:
if (reply[i].data[j].ref == item._id) console.log('match!!!')
The sample of reply & item:
// REPLY
[{
"_id":10,
"data": [
{
"_id":"57f485203858fe43b464ae52",
"type":"product",
"ref":"57f485473858fe43b464ae56",
"name":"KARUNG",
"direction":"in",
"supplier":null,
"information":"PENYESUAIAN JUMLAH",
"qty":200,
"manifest":null,
"timestamp":"2016-10-05T04:44:16.354Z",
"saldo":1200
}
]
}]
// ITEM
{
"_id" : "57f485473858fe43b464ae56",
"name" : "BERAS KC",
"unit" : "SAK",
"qty" : 213,
"weight" : 10
}
I was also trying to convert both to ObjectId using mongojs.ObjectId, but it doesn't work.
The full code snippet: http://pastebin.com/SYTLVWqT

Categories

Resources