Easily create clickable words in Flutter by extracting specific words from a JSON String

In my JSON response, I receive a set of questions. My goal is to split these questions into words and compare them with another JSON response. When there's a match, I want to highlight the matching words and make them clickable to display a pop-up showing the translation from the second response. Ultimately, I want to present both matched and unmatched words in a clickable format resembling the original question.

Here is an example of what I aim to achieve

This is the content of my first JSON:

"status": "true",
"message": "message",
"demo": [
    {
        "qtnNumber": 1,
        "qtnItalian": "Il segnale raffigurato preannuncia un tratto di strada in cui è consentita la manovra di retromarcia",
        "qtnCategory": "SEGNALEI VERTICALI DI PERICOLO",
        "qtnType": true
    },
    {
        "qtnNumber": 2,
        "qtnItalian": "Il segnale strada in cui è consentita la manovra di retromarcia",
        "qtnCategory": "SEGNALEI VERTICALI DI PERICOLO",
        "qtnType": true
    },

This is the content of my second JSON:

{
"status": "true",
"message": "Vocabulary",
"vocabulary": [
    {
        "id": 3406,
        "italian": "a condizione ",
        "punajbi": "ਹਾਲਾਤ ਕੰਡੀਸ਼ਨ",
        "english": "condition",
        "number": null,
        "punjabiEnglish": "halat"
    },
    {
        "id": 3407,
        "italian": "a raso",
        "punajbi": "ਪਲੇਨ            ਇਸ ਦਾ ਬੁੱਕ ਵਿੱਚ ਪੂਰਾ ਲਫ਼ਜ਼ ਹੇ incrocio a raso => ਇਸ ਦਾ ਮਤਲਬ ਪਲੇਨ ਚੌਕ ਇੱਕੋ ਲੈਵਲ ਤੇ ਬਣਿਆ ਹੋਇਆ ਚੌਕ",
        "english": "plane",
        "number": "ikO LEVEL DA CHONK",
        "punjabiEnglish": null

    },
    {
        "id": 3408,
        "italian": "accesso",
        "punajbi": "ਦਾਖਿਲ",
        "english": "Entry",
        "number": null,
        "punjabiEnglish": "Dakhil"
    }

For each question in the first JSON, I plan to extract and match individual words with the Italian field in the second JSON. When a match is found, I will highlight those words accordingly.

Answer №1

import 'dart:convert';

const raw_sentences = '''
{
  "status": "true",
  "message": "message",
  "demo": [
    {
        "qtnNumber": 1,
        "qtnItalian": "Il segnale raffigurato preannuncia un tratto di strada in cui è consentita la manovra di retromarcia",
        "qtnCategory": "SEGNALEI VERTICALI DI PERICOLO",
        "qtnType": true
    },
    {
        "qtnNumber": 2,
        "qtnItalian": "Il segnale strada in cui è consentita la manovra di retromarcia",
        "qtnCategory": "VERTICAL SIGNS OF DANGER",
        "qtnType": true
    }
  ]
}
''';

const raw_vocabulary = '''
{
  "status": "true",
  "message": "Vocabulary",
  "vocabulary": [
    {
      "id": 3406,
      "italian": "a condizione &
      "punajbi": "ਹਾਲਾਤ ਕੰਡੀਸ਼ਨ",
      "english": "condition",
      "number": null,
      "punjabiEnglish": "halat"
    },
    {
      "id": 3500,
      "italian": "preannuncia"
    },
    {
      "id": 3501,
      "italian": "consentita"
    }
  ]
}
''';

void start(List<String> args) {
  var sentence = jsonDecode(raw_sentences)['demo'][0]['qtnItalian'] as String;
  var vocabulary = jsonDecode(raw_vocabulary)['vocabulary'] as List;
  var words = sentence.split(' ');
  var matches = vocabulary.map<String>((m) => (m as Map<String, dynamic>)['italian']).toSet().intersection(words.toSet()).toList();
  var references = Map.fromEntries(List.generate(matches.length, (i) => MapEntry(matches[i], vocabulary.firstWhere((m) => m['italian'] == matches[i])['id']));
  var new_sentence = <Map<String, dynamic>>[];

  var idx = 0;
  words.forEach((word) {
    if (matches.contains(word)) {
      new_sentence.add({'string': word, 'reference': references[word]});
      idx += 2;
    } else {
      if (new_sentence.isEmpty || idx == new_sentence.length) new_sentence.add({});
      new_sentence[idx]['string'] = (new_sentence[idx]['string'] ?? '') + '$word';
    }
  });

  print(sentence);
  print(new_sentence);
}

Output:

The depicted signal predicts a section of road where backing up is allowed
[{string: The illustrated signal}, {string: anticipates, reference: 3500}, {string: a stretch of road in which it is}, {string: allowed, reference: 3501}, {string: the maneuver of reverse}]

By utilizing the new_sentence array, you can generate widgets (texts and buttons) to achieve your objective. Remember, this platform serves to assist, not complete your entire task for you. Have a great day.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transform tree-like JSON array with nested arrays into flat JSON array

I have an array tree in JSON format with potentially unlimited nesting: const namesArrayTree = [ { "name": "Peter" }, { "name": "folder1", "isArray": true, " ...

Guide on accessing a web service using a PHP POST request

Today, I encountered a challenge where I need to access a web service that contains JSON data. In order to do so, I was instructed to utilize the PHP POST method to log into the web service. The instructions included an array with 3 key-value pairs. { " ...

encountering a problem with iterating through a JSON array

After making an ajax call and retrieving select options in json format, I implemented the code below to display these new options in place of the existing ones: success: function (data){ var $select = $('#dettaglio'); $select.html(' ...

Using ng-init to pass a JSON object

I'm attempting to pass a JSON Object to my application using ng-init and the stringify method, but I am encountering an error. Instead of working as expected, I am getting a Lexer error. Lexer Error: Unexpected next character at columns 8-8 [#] in ex ...

Using JQ to structure logs in shell scripting

I've been looking to save some shell scripts into a file for collection by an agent like Fluentbit and sending them off to Cloudwatch and Datadog. I came across this example online that works effectively with the use of jq. __timestamp(){ date &quo ...

How can I verify the status of an occasional undefined JSON value?

There are times when the JSON object I'm trying to access does not exist. Error: Undefined index: movies in C:\xampp\htdocs\example\game.php In game.php, I'm attempting to retrieve it from the Steam API using this code: $ ...

Basic PHP and JSON

Encountering a frustrating issue with my script. It runs smoothly on both my local server and test server, but when I try it on the Rackspace server, it fails to execute correctly. <?php $path = "http://query.yahooapis.com/v1/public/yql?q="; $path .= ...

I'd like to change the name of the JSON key retrieved from the API request

I have a JSON format stored in my database that looks like this. [ { ip.src:"192.168.200.10", y:1506 }, { ip.src:"192.168.200.10", y:1506 }, { ip.src:"192.168.200.10", y:1506 }, { ip ...

Difficulty encountered while extracting information from JSON output

I am new to working with JSON. The more I work with it, the more I find myself liking it. Currently, I have an output that resembles the following structure: [ { "product": { "id": "6", "category": "Books", ...

Ways to resolve the issue of an untraceable image associated with a json mime type

I recently came across this code snippet in my web.config <staticContent> <remove fileExtension=".svg"/> <remove fileExtension=".svgz"/> <remove fileExtension=".eot"/> <remove fileExtension=".otf"/> ...

What is the solution for resolving the Angular error 'Cannot read property "_co.x" of undefined'?

Currently, I am facing an issue with nested JSON objects on a form that sends data to a database. Despite trying the *ngIf statement as recommended in Angular 5 - Stop errors from undefined object before loading data, the view does not update even after th ...

Using Angular's ng-repeat to iterate through an array and display its objects within another array

One of my tasks involves retrieving json objects through a simple post method. The json contains multiple campaigns, organized in an array structure. Each campaign holds slots, which are also arrays with one or more base_image elements. My goal is to di ...

Converting JSON objects into datetime: A step-by-step guide

I am looking for a way to display JSON data in a Kendo chart. Below is the code I have: <head> <meta charset="utf-8"/> <title>Kendo UI Snippet</title> <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019 ...

Unraveling Complex JSON Structures in React

Having trouble reading nested JSON data from a places API URL call? Look no further! I've encountered issues trying to access all the information and nothing seems to be coming through in the console. While unnested JSON is not an issue, nested JSON p ...

Is it possible to utilize $.getJSON() with a machine on the identical subdomain?

My server is called mybox.ourcorp.ourdomain.com. I am attempting to make a JSON request from this server to another server within the same subdomain, specifically http://otherbox.ourcorp.ourdomain.com/feed. When I manually enter this URL in a browser on m ...

Mastering the Art of Binding Variables to Various JSON Types in GOLANG

When it comes to the naming convention of variables in a database, it is customary to use full_name. However, in Postman, the convention dictates using fullName instead. type Person struct { FullName string `json:"fullName"` } Nevertheless, ...

Generate a dynamic drop-down menu by populating it with the names from a JSON array

I'm having trouble populating a drop-down menu with object category names using HTML and jQuery. Can anyone provide some assistance? For example: JSON window.cars = { "compact": [ { "title": "honda", "type": "accord", "thumbnail": " ...

Error when parsing JSON due to the presence of backslashes within the serialized object

When trying to call a server side function and parse the response in client side using JavaScript and Ajax, I encountered a parse error. It seems that the issue lies with the backslash that the JavaScriptSerializer adds to serialize the object. The respons ...

Adding Information to Mongodb with C#

using MongoDB.Bson; using MongoDB.Driver; protected static IMongoClient client; protected static IMongoDatabase db; public async void Insert() { client = new MongoClient(); db = client.GetDatabase("Database"); str ...

retrieving attribute values from JSON objects using JavaScript

I am struggling to extract certain attribute values from a JSON output and use them as input for a function in JavaScript. I need assistance with this task! Below is the JSON data that I want to work with, specifically aiming to extract the filename valu ...