How to map json entities? - json

There is a way to map json objects in react-native? For example, let's say I receive the following object:
{
"dados": {
"ultimaAtualizacao": {
"nome": "Lala"
}
"nascimento": "01/01/2001"
}
}
I want to map it like this:
{
"data": {
"lastUpdate": {
"name": "Lala"
}
"dob": "01/01/2001"
}
}
Considering that fetch returns the first object, this would be possible doing the following code:
myService.get(url).then(response => this.mapObject(response, []));
//Considering state is initialized and I have the mapedEntity to return correct properties
mapObject(jsonObject, parentProperty) {
for (let property in jsonObject) {
if (Array.isArray(jsonObject[property])) {
this.mapArray(jsonObject[property], [...parentProperty,property]); //Would be something like mapObject function
} else if (typeof jsonObject[property] === 'object') {
this.mapObject(jsonObject[property],[...parentProperty,property]);
} else {
let prop = this.state;
for(let k of parentProperty) {
prop = prop[mapedEntity[k]];
}
prop[entidadeMapeada[property]] = jsonObject[property];
}
}
}
There is someway simplier to achieve this?

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);

Mongo: Move json string to a part of the document

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); }

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);

Parsing JSON multi-level array

I want to search in json data with multiple levels of array. My search list return names of my objects but just from the first level. How could i do return all my object's names regardless their levels ?
In this example : OST, OST details, Apocalpse Now, Arizona Dream, Dexter
Data
<script type="application/json" id="dataMusic">
{
"name":"Music",
"level":"1",
"size":36184,
"children":[
{
"name":"OST",
"level":"2",
"size":1416,
"children":[
{
"name":"OST details",
"level":"3",
"size":1416,
"children":[
{
"name":"Apocalypse Now",
"size":15
},
{
"name":"Arizona Dream",
"size":19
},
{
"name":"Dexter",
"size":20
}
]
}
]
}
]
}
</script>
Function
var dataMusic = document.getElementById('dataMusic').innerHTML;
var dataTree = JSON.parse(dataMusic);
var optArray = [];
for (var i = 0; i < dataTree.children.length - 1; i++) {
optArray.push(dataTree.children[i].name);
}
optArray = optArray.sort();
I try this method Parsing Nested Objects in a Json using JS without success
Function
var optArray = [], Music, OST, OST details;
for (Music in dataTree) {
for (OST in dataTree[Music]) {
for (OST details in dataTree[Music][OST]) {
if (OST details in optArray) {
optArray[OST details].push(dataTree[Music][OST][OST details].name)
} else {
optArray[OST details] = [dataTree[Music][OST][OST details].name]
}
}
}
}
You must use nested loops
for Music.children.length
for OST.children.length
for OST details.children.length
Edit : Function
var optArray = [], Music, OST, OST_details;
for (Music in dataTree) {
for (OST in dataTree[Music]) {
for (OST_details in dataTree[Music][OST]) {
if (OST_details in optArray) {
optArray[OST_details].push(dataTree[Music][OST][OST_details].name)
} else {
optArray[OST_details] = [dataTree[Music][OST][OST_details].name]
}
}
}
}
I got it
var dataMusic = document.getElementById('dataMusic').innerHTML;
var dataTree = JSON.parse(dataMusic);
var result = [];
function getAll( input, target ) {
function parseData( input, target ) {
$.each( input, function ( index, obj ) {
if ( index == target ) {
result.push( obj );
}
else {
switch ( $.type( obj ).toLowerCase() ) {
case "object":
case "array":
parseData( obj, target );
break;
}
}
});
}
parseData( dataTree, "name" );
result = result.sort();
return result;
}
alert(JSON.stringify( getAll( dataTree, "name" )));
Thanks to this post :
Parsing multi-level json ; Demo

How to extract all property paths in JSON file having specific value

How can I collect all property paths in a large JSON file containing a specific case-sensitive value?
Here's an example:
JSON:
{
"level1": {
"level1node1": "hit",
"level1node2": "miss",
"level1node3": {
"level2node1" : {
"level3node1": "hit",
"level3node2": {
"level4node1": "miss",
"level4node2": "hit"
}
}
}
}
}
Search text (case-sensitive): "hit"
Return C# string array:
[ "level1.level1node1",
"level1.level1node3.level2node1.level3node1",
"level1.level1node3.level2node1.level3node2.level4node2" ]
I'd like to use JSON.NET to get an array of matching node paths.
This does the trick:
void AddPath(List<string> propertyPaths, JToken jToken, string searchForValue) {
if (jToken is JValue && ((JValue)jToken).Value != null && ((JValue)jToken).Value.ToString() == searchForValue) {
propertyPaths.Add(jToken.Path);
} else if (jToken is JProperty) {
((JProperty)jToken).Values().ToList().ForEach(_ => AddMatch(propertyPaths, _, searchForValue));
} else if (jToken is JObject || jToken is JArray) {
if (jToken.HasValues) {
jToken.Children().ToList().ForEach(_ => AddMatch(propertyPaths, _, searchForValue));
}
}
}