How do I remove a specific element from a JSONArray?
Try this code
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
//Remove the element from arraylist
list.remove(position);
//Recreate JSON Array
JSONArray jsArray = new JSONArray(list);
Edit:
Using ArrayList
will add "\"
to the key and values. So, use JSONArray
itself
JSONArray list = new JSONArray();
JSONArray jsonArray = new JSONArray(jsonstring);
int len = jsonArray.length();
if (jsonArray != null) {
for (int i=0;i<len;i++)
{
//Excluding the item at position
if (i != position)
{
list.put(jsonArray.get(i));
}
}
}
Removing Elements From JSON Array
An alternative you should be aware of is to loop backwards. The problem you are seeing is likely because when you remove an item, the index of every later item changes. The length of the array is decremented too.
But notice that earlier items in the array are not affected. So start at the far end of the array and work your way back towards the start.
And we don't care that the length changes because we only check the length once at the start of the loop, not every iteration.
let obj = { "Times": [{ "TimeStamp": "1588516642", }, { "TimeStamp": "1588516643", }, { "TimeStamp": "1588516644", }]}
for (let i = obj.Times.length - 1; i > -1; i--) { if (obj.Times[i].TimeStamp <= 1588516643) { obj.Times.splice(i, 1); }}
console.log(obj.Times);
Remove specific element from json array
slice()
is your friend.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
json[section] = json[section].slice(index,index+1);
How to delete array element from JSON array of objects by ID
Using Array.filter
, you can filter out elements that don't match a certain condition. For example:
const result = playlists.filter(playlist => playlist.id !== '2');
Here's a working demo:
/* Example Data */
const playlists = [
{
"id" : "1",
"owner_id" : "2",
"song_ids" : [ "8", "32"]
},
{
"id" : "2",
"owner_id" : "3",
"song_ids" : ["6", "8","11" ]
}
];
/* Takes a list of playlists, and an ID to remove */
const removePlaylistById = (plists, id) =>
plists.filter(playlist => playlist.id !== id);
/* Removes playlist ID 2 from list, prints result */
const result = removePlaylistById(playlists, '2');
console.log(result);
Remove specific values in a JSONArray
You can just iterate and remove, try with below - It works fine.
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(
"sample.json"));
JSONArray jsonArray = (JSONArray) obj;
for (int i = 0; i < jsonArray.size(); i++) {
System.out.println("Before --" + jsonArray.get(i).toString());
JSONObject jsonObject = (JSONObject)jsonArray.get(i);
jsonObject.remove("selected");
System.out.println("After --" + jsonArray.get(i).toString());
}
System.out.println("Final Output --" + jsonArray.toString());
Output -
Before --{"selected":true,"nr":1,"grpnr":0,"bezeich":"MORE SALT"}
After --{"nr":1,"grpnr":0,"bezeich":"MORE SALT"}
Before --{"nr":2,"grpnr":0,"bezeich":"MORE SWEET"}
After --{"nr":2,"grpnr":0,"bezeich":"MORE SWEET"}
Before --{"nr":3,"grpnr":0,"bezeich":"MORE PEPPER"}
After --{"nr":3,"grpnr":0,"bezeich":"MORE PEPPER"}
Before --{"selected":true,"nr":4,"grpnr":0,"bezeich":"MORE CHILLI"}
After --{"nr":4,"grpnr":0,"bezeich":"MORE CHILLI"}
Before --{"nr":5,"grpnr":0,"bezeich":"COLD"}
After --{"nr":5,"grpnr":0,"bezeich":"COLD"}
Before --{"nr":6,"grpnr":0,"bezeich":"HOT"}
After --{"nr":6,"grpnr":0,"bezeich":"HOT"}
Before --{"nr":7,"grpnr":0,"bezeich":"SMALL"}
After --{"nr":7,"grpnr":0,"bezeich":"SMALL"}
Before --{"nr":8,"grpnr":0,"bezeich":"LARGE"}
After --{"nr":8,"grpnr":0,"bezeich":"LARGE"}
Before --{"nr":9,"grpnr":0,"bezeich":"MEDIUM COOKED"}
After --{"nr":9,"grpnr":0,"bezeich":"MEDIUM COOKED"}
Before --{"nr":10,"grpnr":0,"bezeich":"WELL DONE"}
After --{"nr":10,"grpnr":0,"bezeich":"WELL DONE"}
Final Output -- [{
"nr": 1,
"grpnr": 0,
"bezeich": "MORE SALT"
}, {
"nr": 2,
"grpnr": 0,
"bezeich": "MORE SWEET"
}, {
"nr": 3,
"grpnr": 0,
"bezeich": "MORE PEPPER"
}, {
"nr": 4,
"grpnr": 0,
"bezeich": "MORE CHILLI"
}, {
"nr": 5,
"grpnr": 0,
"bezeich": "COLD"
}, {
"nr": 6,
"grpnr": 0,
"bezeich": "HOT"
}, {
"nr": 7,
"grpnr": 0,
"bezeich": "SMALL"
}, {
"nr": 8,
"grpnr": 0,
"bezeich": "LARGE"
}, {
"nr": 9,
"grpnr": 0,
"bezeich": "MEDIUM COOKED"
}, {
"nr": 10,
"grpnr": 0,
"bezeich": "WELL DONE"
}]
Remove JSON element
var json = { ... };
var key = "foo";
delete json[key]; // Removes json.foo from the dictionary.
You can use splice to remove elements from an array.
How to remove JSONArray element using Java
What you have there is an array of objects. Therefore you'll have to loop through the array and remove the necessary data from each object, e.g.
for (int i = 0, len = jsonArr.length(); i < len; i++) {
JSONObject obj = jsonArr.getJSONObject(i);
// Do your removals
obj.remove("id");
// etc.
}
I've assumed you're using org.json.JSONObject
and org.json.JSONArray
here, but the principal remains the same whatever JSON processing library you're using.
If you wanted to convert something like [{"id":215},{"id":216}]
to [215,216]
you could so something like:
JSONArray intArr = new JSONArray();
for (int i = 0, len = objArr.length(); i < len; i++) {
intArr.put(objArr.getJSONObject(i).getInt("id"));
}
How to remove an element from a JSON array using Python?
First question
However, whenever there's more than two elements and I enter anything higher than two, it doesn't delete anything. Even worse, when I enter the number one, it deletes everything but the zero index(whenever the array has more than two elements in it).
Inside delete_data()
you have two lines reading i = + 1
, which just assignes +1
(i.e., 1
) to i
. Thus, you're never increasing your index. You probably meant to write either i = i+1
or i += 1
.
def delete_data(): # Deletes an element from the array
view_data()
new_data = []
with open(filename, "r") as f:
data = json.load(f)
data_length = len(data) - 1
print("Which index number would you like to delete?")
delete_option = input(f"Select a number 0-{data_length}: ")
i = 0
for entry in data:
if i == int(delete_option):
i += 1 # <-- here
else:
new_data.append(entry)
i += 1 # <-- and here
with open(filename, "w") as f:
json.dump(new_data, f, indent=4)
Second question: further improvements
Is there a better way to implement that in my Python script?
First, you can get rid of manually increasing i
by using the builtin enumerate
generator. Second, you could make your functions reusable by giving them parameters - where does the filename in your code example come from?
# view_data() should probably receive `filename` as a parameter
def view_data(filename: str): # Prints JSON Array to screen
with open(filename, "r") as f:
data = json.load(f)
# iterate over i and data simultaneously
# alternatively, you could just remove i
for i, item in enumerate(data):
name = item["name"]
chromebook = item["chromebook"]
check_out = item["time&date"]
print(f"Index Number: {i}")
print(f"Name : {name}")
print(f"Chromebook : {chromebook}")
print(f"Time Of Checkout: {check_out} ")
print("\n\n")
# not needed anymore: i = i + 1
# view_data() should probably receive `filename` as a parameter
def delete_data(filename: str): # Deletes an element from the array
view_data()
new_data = []
with open(filename, "r") as f:
data = json.load(f)
data_length = len(data) - 1
print("Which index number would you like to delete?")
delete_option = input(f"Select a number 0-{data_length}: ")
# iterate over i and data simultaneously
for i, entry in enumerate(data):
if i != int(delete_option):
new_data.append(entry)
with open(filename, "w") as f:
json.dump(new_data, f, indent=4)
Furthermore, you could replace that for-loop by a list comprehension, which some may deem more "pythonic":
new_data = [entry for i, entry in enumerate(data) if i != int(delete_option)]
Remove all elements except one from JSONArray of JSONObjects
If you're seeking a functional style solution, you can wrap the Iterator
into a Stream
and then do whatever you want.
One of the functional solutions:
JSONArray newJsonArray =
StreamSupport.stream(jsonArray.spliterator(), false)
.filter(JSONObject.class::isInstance)
.map(JSONObject.class::cast)
.filter(j -> j.has("a"))
.collect(collectingAndThen(toList(), JSONArray::new));
Note: The solution above does not modify the original JSONArray
. Following the principles of functional programming one should prefer collecting into a new object rather than modifying the existing one.
Related Topics
Multiple Commands Through Jsch Shell
Libavcodec.So: Has Text Relocations
Deadobjectexception on Android App
How to Create JSON Object Using String
How to Avoid Unnecessary Firestore Reads with Cache
Android 6.0 (Marshmallow): How to Play Midi Notes
What Does a Java Static Method Look Like in Ruby
Calling a Java Servlet from JavaScript
Difference Between Google() and Maven { Url 'Https://Maven.Google.Com' }
Efficiency of Searching Using Wherearraycontains
Onintercepttouchevent Only Gets Action_Down
How to Remove a Specific Element from a JSONarray
How to Print to the Console in Android Studio
Kotlin-Android: Unresolved Reference Databinding