How to convert string to json in Dart?

by bernard.rippin , in category: Other , 2 years ago

How to convert string to json in Dart?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by percy , 2 years ago

@bernard.rippin you can use dart:convert package to convert or parse any JSON string in Dart, here is the code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import 'dart:convert';

void main() {
    // declare a json string
    var str = '{"id": 1, "username": "test"}';
    
    // convert string to json
    var data = json.decode(str);

    // Output: 1
    print(data['id']);
  
    // Output: test
    print(data['username']);
}
by eda.wolff , 9 months ago

@bernard.rippin 

To convert a string to a JSON object in Dart, you can use the dart:convert library. Here's an example code snippet to demonstrate:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import 'dart:convert';

void main() {
  // A sample JSON string
  String jsonString = '{"name": "John", "age": 30}';

  // Convert the string to a JSON object
  Map jsonObject = jsonDecode(jsonString);

  // Access the object's properties
  print(jsonObject['name']); // Output: "John"
  print(jsonObject['age']); // Output: 30
}


In this example, we use the jsonDecode() function from the dart:convert library to convert the JSON string into a Map object. We can then access the properties of the JSON object using the keys in the Map.