2

I have a json String {"a":"{\"b\":7}"}. But it does not get decoded from the default library. I have written the following code:

import 'dart:convert';
void main() {
  String a =
        '{"a":"{\"b\":7}"}';
   print(json.decode(a));
}

Please help to parse the json.

2
  • Why does 'b' only have a backslashes and quotation mark? Commented Oct 4, 2021 at 13:58
  • Basically there is a json inside the main json. It is a long json, but for simplicity I have posted this simplified version of it. Commented Oct 4, 2021 at 14:03

2 Answers 2

2

To work with JSON objects that have deep/multiple levels/recursive dot notation, then you can use a fantastic Dart package: g_json. I find it super easy and simple!

It doesn't use generated code as on Flutter recommended packages for JSON and these are complicated. Dart & Flutter teams have to improve.


I use a complex JSON object and your example and I show you how I access the data (you have to clean your JSON string, maybe your example is copied from a place that add extra double quotes " " on brackets).

Now, look at my code:

import 'dart:convert';
import 'package:g_json/g_json.dart';

void main() {
  String jsonSimple = '{"a":"1"}';

  // Get value from only one level JSON object.
  final Map<String, dynamic> resultSimple = json.decode(jsonSimple);
  print(resultSimple);

  // Your example with some cleaning.
  String jsonExample = jsonEncode({
    "a": {"b": 7}
  });
  var resultDeep = JSON.parse(jsonExample);
  print(resultDeep['a']['b'].rawString());

  // Deep JSON object
  // This is a real JSON data from api.openweathermap.org/data/2.5/weather?q=Barcelona&appid=<your_api_key>. You can try it on your browser, put it on the url and press `ENTER`.
  String jsonWeather = jsonEncode({
    "coord": {"lon": 2.159, "lat": 41.3888},
    "weather": [
      {
        "id": 803,
        "main": "Clouds",
        "description": "broken clouds",
        "icon": "04d"
      }
    ],
    "base": "stations",
    "main": {
      "temp": 291.21,
      "feels_like": 291.11,
      "temp_min": 289.53,
      "temp_max": 293.62,
      "pressure": 1016,
      "humidity": 78
    },
    "visibility": 10000,
    "wind": {"speed": 0.45, "deg": 212, "gust": 1.79},
    "clouds": {"all": 75},
    "dt": 1633360018,
    "sys": {
      "type": 2,
      "id": 18549,
      "country": "ES",
      "sunrise": 1633326668,
      "sunset": 1633368526
    },
    "timezone": 7200,
    "id": 3128760,
    "name": "Barcelona",
    "cod": 200
  });
  print(jsonWeather);
  // It prints: `String`
  print(jsonWeather.runtimeType);
  resultDeep = JSON.parse(jsonWeather);
  print(resultDeep['wind']['speed'].rawString());
  print(resultDeep['weather'][0]['main'].rawString());

  // Extract data for each item of the array.
  final List<dynamic> listJsonWeather = resultDeep['weather'].value;
  List<WeatherEntity> listWeathers = [];
  for (dynamic jsonWeather in listJsonWeather) {
    listWeathers.add(WeatherEntity(
      id: jsonWeather['id'].toString(),
      title: jsonWeather['main'] as String,
      overview: jsonWeather['description'] as String,
      image: '<url>/${jsonWeather['icon']}',
    ));
  }
}

The console prints the next outcome:

7
String
0.45
"Clouds"

Tips

You can use Postman to fetch API data from services. A very useful tool, trust me!

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

I implemented with your json string.

enter image description here

import 'dart:convert';
void main() {
  String a = '{"a":"{\"b\":7}"}';
  String b = a.replaceAll(RegExp(r'\\\""'), "\"");
  b = b.replaceAll(RegExp(r'\"{'), "\{");
  b = b.replaceAll(RegExp(r'\"}'), "\}");
  print(b);
  print(json.decode(b));
}

2 Comments

I need to keep the inner json intact. So print(json.decode(json.decode(b)['a'])); throws the error.
r'{"a":"{\"b\":7}"}' or '{"a":"{\\\"b\\\":7}"}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.