How to check does not exists properties in nested json - json

my json structure is:
{
"bob": {"blue": 2 }
}
next i did this for checking does not exists properties:
if(myArray['alice']['red] === false) {
console.log('undefined');
}
then it returns "Cannot read property 'red' of undefined"

try this code:
var arr = {
"bob": {"blue": 2 }
}
if(!arr['alice']) {
console.log('undefined');
}
else if (!arr['alice']['red']) {
console.log('undefined');
}

Related

How to map json entities?

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?

json and cors with akka http

I have a post message. I use akka-http.
And I have to call this route from an another server.
So I have to add cors with HttpOriginRange.* with ch.megard.akka.http.cors.CorsDirectives.
The answer is a json.
And I want to have a ContentType application/json
How can I do that?
Here is my route code :
settings = CorsSettings.defaultSettings.copy(allowGenericHttpRequests = true, allowCredentials = false, allowedOrigins = HttpOriginRange.*)
val route: Route =
handleRejections(CorsDirectives.corsRejectionHandler) {
cors(settings) {
handleRejections(RejectionHandler.default) {
post {
authenticated(doAuthApp) { app =>
complete("success")
}
}
}
}
}
I tried this :
val route: Route =
handleRejections(CorsDirectives.corsRejectionHandler) {
cors(WebServer.settings) {
handleRejections(RejectionHandler.default) {
(decodeRequest & encodeResponse) {
mapResponseEntity(_.withContentType(ContentTypes.`application/json`)) {
post {
authenticated(doAuthApp) { app =>
complete("success")
}
}
}
}
}
}
}
If I do that I have an error : Unexpected 's'
Could you help me please?
If you try
var settings = CorsSettings.defaultSettings.copy(allowGenericHttpRequests = true, allowCredentials = false, allowedOrigins = HttpOriginRange.*)
val route =
pathPrefix("testEndpoint") {
handleRejections(CorsDirectives.corsRejectionHandler) {
cors(settings) {
handleRejections(RejectionHandler.default) {
post {
entity(as[String]) {
app =>
complete("success")
}
}
}
}
}
}

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

JSON - Checking for a property in a deeply nested JSON

JSON structure:
{
"codes":[
{
"id":"1",
"code":{
"fname":"S",
"lname":"K",
"dateofbirth":{
"month":"12",
"day":"02",
"year":"1998"
}
}
},
{
"id":"2",
"code":{
"fname":"M",
"lname":"D",
"dateofbirth":{
"month":"10",
"day":"02",
"year":"1998"
}
}
}
]
}
I want to loop through each code AND dateofbirth and alert if the month is 12. If the month is not 12, then do nothing.
success: function(data){
var x;
for (x = 0; x < data.codes.length; x++){
var count=0;
for (property in data.codes[x].code) {
count++;
}
}
}
How can I loop through dateofbirth and check for the value of month?
Example of JSON structure with more than 1 property under 'code' that can be an object. So I want to loop through all the properties within code and check for the value of the month property instead of manually checking for a particular property.
{
"codes":[
{
"id":"1",
"code":{
"fname":"S",
"lname":"K",
"dateofbirth":{
"month":"12",
"day":"02",
"year":"1998"
},
"membership":{
"month":"12",
"day":"12",
"year":"2011"
}
}
},
{
"id":"2",
"code":{
"fname":"M",
"lname":"D",
"dateofbirth":{
"month":"10",
"day":"02",
"year":"1998"
},
"membership":{
"month":"10",
"day":"12",
"year":"2011"
}
}
}
]
}
mycodes=// the object from parsed JSON
for (i=0; i<mycodes.codes.length; i++) {
if (mycodes.codes[i].code.dateofbirth.month=="12") {
alert("Code " + mycodes.codes[i].id + " has birth month of 12");
}
}
BTW, you really should store birthdates as numbers, not strings.