1
  • I have a JSON having some data as an array , and I wanna add new data to JSON

This is My JSON structure

```[
{
"id":"JKT020",
"origin_time":"2020-06-30 12:00",
"location":"Jakarta, ID"
}
]```

I want to add new data so it can be like this

 ```[
{
"id":"JKT020",
"origin_time":"2020-06-30 12:00",
"location":"Jakarta, ID",
"flag":1
}
]```

Is it possible ? If it is can anyone tell me how to do that ? Thanks in advance.

And this is what I've been doing so far..

List data = json.decode(response.body);
      for (int i = 0; i < data.length; i++) {
        data.add(data[i]["flag"]=1);
        print("object : " + data[i].toString());
      }
      });

It was printed like I want it, but return error in add line

The error said NoSuchMethodError: Class 'String' has no instance method '[]='

2 Answers 2

3

First of all, you have to Decode the JSON

var data=json.decode("Your JSON")

Now this is available as a list and map so you can add fields like

data[key]=value;

after that, you have to Encode it using json.encode

var data1=json.encode(data); `

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

Comments

0

It's a good idea to get the JSON formatted and mapped to a Model. This will not only help to do null checks but also increase the readability of your code.

You can use a simple Model like

class myModel {
  String id;
  String originTime;
  String location;
  int flag;

  myModel({this.id, this.originTime, this.location, this.flag});

  myModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    originTime = json['origin_time'];
    location = json['location'];
    flag = json['flag'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['origin_time'] = this.originTime;
    data['location'] = this.location;
    data['flag'] = this.flag;
    return data;
  }
}

Comments

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.