Dart Requires Chilkat v11.0.0+
Dart
Modify Parts of JSON Document
See more JSON Examples
Demonstrates how to modify parts of a JSON document. This example uses the following JSON document:
{
"fruit": [
{
"kind": "apple",
"count": 24,
"fresh": true,
"extraInfo": null,
"listA": [ "abc", 1, null, false ],
"objectB": { "animal" : "monkey" }
},
{
"kind": "pear",
"count": 18,
"fresh": false,
"extraInfo": null
"listA": [ "xyz", 24, null, true ],
"objectB": { "animal" : "lemur" }
}
],
"list" : [ "banana", 12, true, null, "orange", 12.5, { "ticker": "AAPL" }, [ 1, 2, 3, 4, 5 ] ],
"alien" : true
}
Chilkat Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
final json = CkJsonObject();
// Load the JSON from a file.
try {
json.loadFile('qa_data/json/modifySample.json');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
// This example will not check for errors (i.e. null / false / 0 return values)...
// Get the "list" array:
final listA = CkJsonArray();
json.arrayOf2('list', listA);
// Modify values in the list.
// Change banana to plantain
listA.setStringAt(0, 'plantain');
// Change 12 to 24
listA.setIntAt(1, 24);
// Change true to false
listA.setBoolAt(2, false);
// Is the 3rd item null?
// Change "orange" to 32.
listA.setIntAt(4, 32);
// Change 12.5 to 31.2
listA.setNumberAt(5, '31.2');
// Replace the { "ticker" : "AAPL" } object with { "ticker" : "GOOG" }
// Do this by deleting, then inserting a new object at the same location.
listA.deleteAt(6);
final tickerObj = CkJsonObject();
listA.addObjectAt2(6, tickerObj);
tickerObj.appendString('ticker', 'GOOG');
// Replace "[ 1, 2, 3, 4, 5 ]" with "[ "apple", 22, true, null, 1080.25 ]"
listA.deleteAt(7);
final aa = CkJsonArray();
listA.addArrayAt2(7, aa);
aa.addStringAt(-1, 'apple');
aa.addIntAt(-1, 22);
aa.addBoolAt(-1, true);
aa.addNullAt(-1);
aa.addNumberAt(-1, '1080.25');
// Get the "fruit" array
final aFruit = CkJsonArray();
json.arrayAt2(0, aFruit);
// Get the 1st element:
final appleObj = CkJsonObject();
aFruit.objectAt2(0, appleObj);
// Modify values by member name:
appleObj.setStringOf('fruit', 'fuji_apple');
appleObj.setIntOf('count', 46);
appleObj.setBoolOf('fresh', false);
appleObj.setStringOf('extraInfo', 'developed by growers at the Tohoku Research Station in Fujisaki');
// Modify values by index:
final pearObj = CkJsonObject();
aFruit.objectAt2(1, pearObj);
pearObj.setStringAt(0, 'bartlett_pear');
pearObj.setIntAt(1, 12);
pearObj.setBoolAt(2, false);
pearObj.setStringAt(3, 'harvested in late August to early September');
json.emitCompact = false;
print(json.emit());
}