Miguel
Miguel

Reputation: 35

Search if exists on local JSON and show new value flutter

I have a code that looks like this

aa.json

[  {
    "old_value": "992812738823",
    "new_value": "4661"
  },
  {
    "old_value": "992112734423",
    "new_value": "9901"
  }]


    final String response = await rootBundle.loadString('assets/json/aa.json');
    

    var json = jsonDecode(response) as Map;



      if (json.containsValue(scanResult)) { //scanResult example = 992812738823
        print('has the value');
        print('The new value is: $json['new_value']'); 
      } else {
        print('no value');

      }
/*

scanResult is getted random from an item as a string.

But I'm having hard time displaying only the info that I want.

Upvotes: 0

Views: 63

Answers (2)

mezoni
mezoni

Reputation: 11200

This code will works.

void main() {
  final data = Map.fromEntries((_apiData as List)
      .map((e) => e as Map)
      .map((e) => MapEntry(e['old_value'], e['new_value'])));
  final oldValue = '992812738823';
  if (data.containsKey(oldValue)) {
    print('New value: ${data[oldValue]}');
  }
}

const _apiData = [
  {"old_value": "992812738823", "new_value": "4661"},
  {"old_value": "992112734423", "new_value": "9901"}
];

Output:

New value: 4661

Upvotes: 0

Mahi
Mahi

Reputation: 1732

You can use below code for parsing your json.

final welcome = welcomeFromJson(jsonString);

// To parse this JSON data, do
//
//     final welcome = welcomeFromJson(jsonString);

import 'dart:convert';

List<Welcome> welcomeFromJson(String str) => List<Welcome>.from(json.decode(str).map((x) => Welcome.fromJson(x)));

String welcomeToJson(List<Welcome> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Welcome {
    Welcome({
        this.oldValue,
        this.newValue,
    });

    String oldValue;
    String newValue;

    factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
        oldValue: json["old_value"],
        newValue: json["new_value"],
    );

    Map<String, dynamic> toJson() => {
        "old_value": oldValue,
        "new_value": newValue,
    };
}

Upvotes: 1

Related Questions