How to use if statement inside JSON?
That's regular JavaScript, not JSON. Move the if
statement outside:
if (page) {
var config = [
{
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
}, {
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
}
];
} else {
var config = [
{
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
}
];
}
Is it possible to use an if-else statement inside a JSON file?
JSON is only a data representation (unrelated to any programming language, even if early JavaScript implementations remotely inspired it). There is no notion of "execution" or "conditional" (or of "behavior" or of "semantics") in it.
Read carefully the (short) JSON definition. It simply defines what sequence of characters (e.g. the content of a file) is valid JSON. It does not define the "meaning" of JSON data.
JSON data is parsed by some program, and emitted by some program (often different ones, but could be the same).
The program handling JSON can of course use conditions and give some "meaning" (whatever is the definition of that word) to it. But JSON is only "data syntax".
You could (easily) write your own JSON transformer (using some existing JSON library, and there are many of them), and that is really simple. Some programs (notably jq) claim to be more or less generic JSON processors.
Since JSON is a textual format, you could even use some editor (such as emacs, vim or many others) to manually change parts of it. You'll better validate the result with some existing JSON parser (to be sure you did not add any mistakes).
JSON If Statement
This will update your json based on "ReplacementAmount"
var lineitemobject = JSON.parse('{"recordtype":"salesorder","item":[{"InventoryManagementKey":"20001","InvoiceDay":"9/10/2015","ReplacementAmount":0.0000,"ReplacementCount":500,"ServiceAmount":0.0000,"ServiceCount":0}]}');
if(lineitemobject.item[0]['ReplacementAmount'] > 0) {
lineitemobject.item[0]['quantity'] = lineitemobject.item[0]['ReplacementAmount'];
delete lineitemobject.item[0]['ReplacementAmount'];
} else {
lineitemobject.item[0]['quantity'] = lineitemobject.item[0]['ServiceCount'];
delete lineitemobject.item[0]['ServiceCount'];
}
Here only lineitemobject JavaScript object value changes, not the JSON string.
Using JSON objects in 'if' statements?
Inside a template string, only expressions are allowed, not statements. if
is a statement; but there's the conditional operator (?:
) which has almost the same semantics.
`...
<div class="role">${player.steamid == 'Rex4748' ? 'Owner' : 'Moderator'}</div>
...`
If statement inside PHP object
As mentioned by knittl you could check if a specific value is null and not add it to your object.
If it is necessary though to dynamically create objects withouth the hustle of checking. You have to use array_filter
or any other custom filtering function for that.
I wrote a custom filtering function that accepts a deeply nested array and returns it back filtered.
function arrayFilter($inputArr){
$output = null;
if (is_array($inputArr)){
foreach ($inputArr as $key=>$val){
if(!$inputArr[$key]) continue;
if (is_array($val)) {
$tmpArr = arrayFilter($val);
if($tmpArr) $output[$key] = array_filter($tmpArr);
}
else $output[$key] = $val;
}
} else {
$output[$key] = $val;
}
return $output;
}
So, lets say you have a deeply nested object similar to the one you provided
$obj = (object) [
"id" => null,
"Name" => (object) [
"eng_name" => strval('some name2'),
"de_name" => null,
"more" => (object) [
"fr_name" => strval('some name3'),
"ru_name" => null,
]
]
];
Below i convert the stdClass object you have to an array with json_encode
and json_decode
and if you pass it as a parameter into the function like:
$filtered = arrayFilter(json_decode(json_encode($obj), true));
Your output will be something like the following:
{
"Name":{
"eng_name":"some name2",
"more":{
"fr_name":"some name3"
}
}
}
Python - IF statement inside a for loop checking on a Json File
def SumOfNegWords(wordsInTweet):
f = open ('wordList.json')
wordList = json.load(f)
NegAmount = 0
for words in wordsInTweet: #for words in the input
if words in wordList['negative']:
NegAmount += 1
print("The Sum of Negative Words =", NegAmount)
else:
print("No negative words found")
changed it a bit... words
in if condition because that's what you're iterating over and indentation in else
Want to use IF statement with JSON
Test this example
var data = [{ "id": "1", "itemName": "exampleItem1"}, { "id": "2", "itemName": "exampleItem2"}];var ul = "<ul>";for (var i = 0; i < data.length; i++) { ul += "<li>" + '1/2 tsp salt' + "</li>" + "<li>" + '2 cups ' + (data[i].id == "2" ? data[i].itemName : " ") + "</li>" + "<li>" + data[i].itemName + "</li>";
}ul += "</ul>";document.body.innerHTML = ul;
Related Topics
Dynamically Increase and Decrease an Input Text Box Size Depending on Another Selector Width
How to Play Audio File into Channel
How to Delete a Localstorage Item When the Browser Window/Tab Is Closed
Webpack: Module Not Found: Error: Can't Resolve (With Relative Path)
How to Change the Font Color, Font Size, and Button Color in React
How to Get Date Value from One Date Input Field and Put It to Other Date Field Using JavaScript
How to Hide Div When You Scroll to Bottom and Show It Again When Scroll Up to Top
Trigger Event When Element Becomes Visible With Ngif
Jquery, Line Break in Textarea.. Don't Get \N and Get ↵
React Native Dynamically Change View's Background Color
React Wait Until Set State in the Same Function
How to Disable Clicking Inside Div
Opening Pdf String in New Window With JavaScript
How to Clear Input After Onclick With Reactjs
How to Make a Bot Delete Messages After a Certain Time Period
Regex to Replace Everything Except Numbers and a Decimal Point