I have an array of json in my response
{"took":0,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":51,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"log4j-2022.01.25","_type":"log4j_type","_id":"x5AWkX4BkHwsqoJA8hbA","_score":1.0,"_source":{"@timestamp":"2022-01-25T11:55:07.221Z","commands":"wc,trim,uniq,sort","message":"2022-01-25 17:25:06 wc,trim,uniq,sort sharon","@version":"1","host":"sharon","time":"2022-01-25 17:25:06","username":"sharon","path":"/home/sharon/Log/Logging.log"}},
[{"_index":"log4j-2022.01.25","_type":"log4j_type","_id":"yJAXkX4BkHwsqoJAAhZi","_score":1.0,"_source":{"@timestamp":"2022-01-25T11:55:11.224Z","commands":"wc,sort,trim,uniq","message":"2022-01-25 17:25:10 wc,sort,trim,uniq sharon","@version":"1","host":"sharon","time":"2022-01-25 17:25:10","username":"sharon","path":"/home/sharon/Log/Logging.log"}},
...]}}
I just want the username and commands field from the each json object. I've fetched the data using axios. How can I do it?
const query = {
query: {
match_all: {},
},
_source: ["time"],
};
axios
.get("http://localhost:9200/log4j-2022.01.25/_search", query)
.then((res) => {
console.log(res.data);
});
Much appreciated
There seems to be a [ floating in your JSON that does not belong there. If this is indeed the case, then this code would retrieve the username and commands properties:
let result = res.data.hits.hits.map(
({_source: {commands, username}}) => ({commands, username})
);
For the given sample data this will set result to:
[
{ "commands": "wc,trim,uniq,sort", "username": "sharon" }
{ "commands": "wc,sort,trim,uniq", "username": "sharon" }
]
const { hits } = res.data.hits
const remapped = hits.map((element) => ({commands: element._source.commands, username: element._source.username}))