Mongo: Move json string to a part of the document - json

I have a mongo collection where documents have aprox the following structure:
item{
data{"emailBody":
"{\"uniqueKey\":\" this is a stringified json\"}"
}
}
What I want to do is to use 'uniqueKey' as an indexed field, to make an "inner join" equivalant with items in a different collection.
I was thinking about running a loop on all the documents -> parsing the json -> Saving them as new property called "parsedEmailBody".
Is there a better way to handle stringified json in mongo?

The only way is to loop through the collection, parse the field to JSON and update the document in the loop:
db.collection.find({ "item.data.emailBody": { "$type": 2 } })
.snapshot().forEach(function(doc){
parsedEmailBody = JSON.parse(doc.item.data.emailBody);
printjson(parsedEmailBody);
db.collection.updateOne(
{ "_id": doc._id },
{ "$set": { "item.data.parsedEmailBody": parsedEmailBody } }
);
});
For large collections, leverage the updates using the Bulk API:
var cursor = db.collection.find({ "item.data.emailBody": { "$type": 2 } }).snapshot(),
ops = [];
cursor.forEach(function(doc){
var parsedEmailBody = JSON.parse(doc.item.data.emailBody);
ops.push({
"updateOne": {
"filter": { "_id": doc._id },
"update": { "$set": { "item.data.parsedEmailBody": parsedEmailBody } }
}
});
if (ops.length === 500) {
db.collection.bulkWrite(ops);
ops = [];
}
});
if (ops.length > 0) { db.collection.bulkWrite(ops); }

Related

Extract parameters from nested Json

I have an json string, which looks like this:
{
\"request\": {
\"requestId\": \"dd92f43ec593d2d8db94193b7509f5cd\",
\"notificationType\": \"EntityAttribute\",
\"notificationSource\": \"ODS\"
},
\"entityattribute\": {
\"entityId\": \"123\",
\"attributeType\": \"DATE_OF_BIRTH\"
}
}
I want to deserialized entityattribute to an object:
public class EntityAttributeNotification {
private String attributeType;
private String entityId;
}
One way is to extract entityId and attributeType first using the json path(i.e entityattribute/entityId)and create an object EntityAttributeNotification.
I want to know if there is a way to directly deserialized entityattribute to EntityAttributeNotification.
I have also tried with JsonMixin annotation but this does not apply here.
Through the following method you can extract Parameters and Values of nested JSON .
const object1 ={
"request": {
"requestId": "dd92f43ec593d2d8db94193b7509f5cd",
"notificationType": "EntityAttribute",
"notificationSource": "ODS"
},
"entityattribute": {
"entityId": "123",
"attributeType": "DATE_OF_BIRTH"
}
};
var keys = [];
for (let [key, value] of Object.entries(object1)) {
if(typeof value == 'object'){
keys.push(key);
for (let [key1, value1] of Object.entries(value)) {
keys.push(key1);
}
}
else{
keys.push(key);
}
}
console.log(keys);

How to access data inside a complex JSON object in Dart?

I use a WebSocket to communicate to a server in my Flutter app. Let's say I receive a JSON object trough the WebSocket :
{
"action": "getProduct",
"cbackid": 1521474231306,
"datas": {
"product": {
"Actif": 1,
"AfficheQte": 0,
"Article": "6"
},
"result": "success"
},
"deviceID": "4340a8fdc126bb59"
}
I have no idea what the content of datas will be until I read the action, and even then, it's not guaranteed to be the same every time. One example of a changing action/datas is when the product doesn't exist.
I can parse it in a Map<String, Object>, but then, how do I access what's inside the Object?
What's the correct way to read this data?
Not sure what the question is about, but you can check the type of the values and then continue accordingly
if(json['action'] == 'getProduct') {
var datas = json['datas'];
if(datas is List) {
var items = datas as List;
for(var item in items) {
print('list item: $item');
}
} else if (datas is Map) {
var items = datas as Map;
for(var key in items.keys) {
print('map item: $key, ${items[key]}');
}
} else if(datas is String) {
print('datas: $datas');
} // ... similar for all other possible types like `int`, `double`, `bool`, ...
}
You also can make that recursive to check list or map values if they are String, ...

How can I create an array from a json object?

My json looks like this, it consists of objects and a few other properties:
let jsonobject = {
"one":{ id:'Peter'},
"two":{ id:'John'},
"three":{ id:'Ko'},
"id":1,
"name":'Jack'
}
I want to convert this to an array with lodash or something, the result would be:
[{ id:'Peter'},
{ id:'John'},
{ id:'Ko'}]
So I can use _.values(jsonobject) but how can I ditch the id and the name property which are obviously no objects? I want a compact solution and/or use lodash.
(1) Get all values for the outer object, (2) filter non object items.
_.filter(_.values(jsonobject), _.isObject)
Or alternatively the chained variant:
_(jsonobject).values().filter(_.isObject).value()
You can simply use filter with an isObject predicate to get the values.
var result = _.filter(jsonobject, _.isObject);
let jsonobject = {
"one": {
id: 'Peter'
},
"two": {
id: 'John'
},
"three": {
id: 'Ko'
},
"id": 1,
"name": 'Jack'
};
var result = _.filter(jsonobject, _.isObject);
console.log(result);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
You can loop over the key in your object and store those that are objects in an array.
var obj = {
"one":{ id:'Peter'},
"two":{ id:'John'},
"three":{ id:'Ko'},
"id":1,
"name":'Jack'
};
var arr = [];
for(var key in obj){
if(typeof obj[key] === 'object'){
arr.push(obj[key]);
}
}
console.log(arr);

How to get key and value separately from json in node js

I have a json like this
{"Beauty_Personal_Care": {
"listingVersions": {
"v1": {
"get": "http://affiliate-feeds.snapdeal.com/feed/api/category/v1:586:680986904635?expiresAt=1455143400082&signature=gtvuofdhkeqxipadfzyf"
}
}
},
"Eyewear": {
"listingVersions": {
"v1": {
"get": "http://affiliate-feeds.snapdeal.com/feed/api/category/v1:473:630636448881?expiresAt=1455143400082&signature=gtvuofdhkeqxipadfzyf"
}
}
}
}
I want to get key value and objects of key value separately in node js backend.
Expected result:
name="Beauty_Personal_Care";
url="http://affiliate-feeds.snapdeal.com/feed/api/category/v1:586:680986904635?expiresAt=1455143400082&signature=gtvuofdhkeqxipadfzyf";
var json = {}; // your json
var result = [];
Object.keys(json).forEach(function (name) {
var data = {
name: name
};
data.url = json[name].listingVersions.v1.get;
result.push(data);
});
console.log(result);

coldfusion json parsing issue

I have the following json string and need to extract each of the survey_id values as a list. ie 74448500, 74052991, 65442357
{
"status":0,
"data":{
"surveys":[
{
"survey_id":"74448500"
},
{
"survey_id":"74052991"
},
{
"survey_id":"65442357"
}
],
"page":1,
"page_size":1000,
"metadata":{
"collaboration":{
"shared_by_total":0,
"unfiled_owned_total":143,
"shared_with_total":0,
"owned_total":242
}
}
}
}
Not sure what version of ColdFusion you are on, here are two possible ways to do it:
<cfscript>
x = deserializeJSON('{"status":0,"data":{"surveys":[{"survey_id":"74448500"},{"survey_id":"74052991"},{"survey_id":"65442357"}],"page":1,"page_size":1000,"metadata":{"collaboration":{"shared_by_total":0,"unfiled_owned_total":143,"shared_with_total":0,"owned_total":242}}}}');
// ColdFusion 11
y = x.data.surveys.map(function(item){
return item.survey_id;
});
writeDump(arrayToList(y));
// ColdFusion 9+
z = [];
for (item in x.data.surveys) {
arrayAppend(z, item.survey_id);
}
writeDump(arrayToList(z));
</cfscript>