Home > front end >  JSON extract date from matching string
JSON extract date from matching string

Time:06-23

I am entirely new to JSON, and haven't got any familiarity with it at all. I'm tinkering around with some JSON data extracts to get a feel for it.

Currently, I have a chat export which has a large number of keys. Within these keys are a "date" key, and a "from_id" key.

I would like to search a JSON file for a matching value on the "from_id" key, and return all the values against the "date" keys with a matching "from_id" value.

For example:

{
 "name": "FooBar Chat Group",
 "type": "textchat",
 "id": 123456789,
 "messages": [
  {
{
   "id": 252930,
   "type": "message",
   "date": "2021-03-03T01:39:30",
   "date_unixtime": "1614735570",
   "from": "Person1",
   "from_id": "user1234",
   "text": "This is a message!"
  },
  {
   "id": 252931,
   "type": "message",
   "date": "2021-03-03T01:41:03",
   "date_unixtime": "1614735663",
   "from": "Person2",
   "from_id": "user9876",
   "text": "This is a reply!"
  },
  {
   "id": 252932,
   "type": "message",
   "date": "2021-03-03T01:42:01",
   "date_unixtime": "1614735721",
   "from": "Person2",
   "from_id": "user9876",
   "text": "This is some other text!"
  },
  {
   "id": 252933,
   "type": "message",
   "date": "2021-03-03T01:42:44",
   "date_unixtime": "1614735764",
   "from": "Person1",
   "from_id": "user1234",
   "text": "Yeah, indeed it is!"
  }
 ]
}

I want to search from_id "user1234", and for it to return the following:

  • 2021-03-03T01:39:30
  • 2021-03-03T01:42:44

These are the two dates that have a matching from_id.

How would I go about doing something like this, please?

I am entirely new to this, so a super basic explanation with resources would really be appreciated. Thanks!

CodePudding user response:

you can try this c# code. At first you have to parse your json strig to create an object from string. Then you can use LINQ to get the data you need

using Newtonsoft.Json;

JArray messages = (JArray) JObject.Parse(json)["messages"];

string from_id="user1234";

DateTime[] dates = messages
                .Where(m=> (string) m["from_id"] ==from_id)
                .Select(m => (DateTime) m["date"])
                .ToArray();

CodePudding user response:

Assuming your sample is part of a JSON Array - starts with [ and ends with ] - you should be able to iterate and conditionally select what you want.

In javascript, you can use a for of to iterate through and an if to match your request:

for(let item of array){
  if(item['from_id'] == 'user1234')
    console.log(item.date);
}

As we don't know the language you're actually using, a more wide code version of it could be something like:

for(let i=0;i < array.length; i  ){
  if(array[i]['from_id'] == 'user1234'){
    print(array[i]['date']);
  }
}
  • Related