I have two long JSON string and what I need is compare these strings and find if they are equals or not, if it's not equal I can get list1 which contains (JSON1-JSON2) and list2 contains (JSON2-JSON1)
I find this ( https://github.com/google/dart-json_diff ) but it's very annoying and I don't know how to use this
I mean something like this
final json1 = await http.get('https://jsonplaceholder.typicode.com/posts');
final json2 = await http.get('https://jsonplaceholder.typicode.com/posts');
var list1= compare(json1,json2);
var list2= compare(json2,json1);
List<dynamic> compare (List<dynamic> json1,List<dynamic> json1){
.
.
code?
.
.
return results;
}
/////////////////
json1=[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
},
{
"userId": 1,
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
},
]
/////////////////
json2=[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat ",
"body": "quia et suscipit\nsuscipit recusandae"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi "
},
{
"userId": 1,
"id": 3,
"title": "ea molestias quasi",
"body": "et iusto sed quo iure\nvoluptatem occaecati"
},
{
"userId": 1,
"id": 4,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi "
},
]
//////////
list1=[
{
"userId": 1,
"id": 4,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi "
},
]
thank u
Ok 👍 this code working for me:
Future<String> _loadTestDataAssetsCloud() async {
return await rootBundle.loadString('assets/testDataCloud.json');
}
Future<String> _loadTestDataAssetsUrl() async {
return await rootBundle.loadString('assets/testDataUrl.json');
}
Future testData() async {
var jsonUrl = await _loadTestDataAssetsUrl();
Map decodedUrl = jsonDecode(jsonUrl);
List<dynamic> individualsUrl = (((decodedUrl['CONSOLIDATED_LIST']
as Map)['INDIVIDUALS'] as Map)['INDIVIDUAL']);
var jsonCloud = await _loadTestDataAssetsCloud();
Map decodedCloud = jsonDecode(jsonCloud);
List<dynamic> individualsCloud = (((decodedCloud['CONSOLIDATED_LIST']
as Map)['INDIVIDUALS'] as Map)['INDIVIDUAL']);
List<dynamic> newList = [];
List<dynamic> delList = [];
individualsUrl.forEach((itemUrl) {
bool a = true;
individualsCloud.forEach((itemCloud) {
if (itemUrl['REFERENCE_NUMBER'] == itemCloud['REFERENCE_NUMBER']) {
a = false;
}
});
if (a == true) {
newList.add(itemUrl);
}
});
print('newList');
// print(newList);
print(newList.length);
newList.forEach((f){
print(f['REFERENCE_NUMBER']);
});
individualsCloud.forEach((itemCloud) {
bool d = true;
individualsUrl.forEach((itemUrl) {
if (itemCloud['REFERENCE_NUMBER'] == itemUrl['REFERENCE_NUMBER']) {
d = false;
}
});
if (d == true) {
delList.add(itemCloud);
}
});
print('delList');
// print(delList);
print(delList.length);
delList.forEach((f){
print(f['REFERENCE_NUMBER']);
});
}
Related
I am receiving the following error when executing a JSON get request:
Thread 6: Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "id", intValue: nil)], debugDescription: "Expected to decode String but found a number instead.", underlyingError: nil))
Here is the code I am using that makes the fetch request:
struct Get: Codable, Identifiable {
var id = UUID()
var title: String
var body: String
//var meals: [[String: String?]]
//var strInstructions: String
}
class Api {
func getData(completion: #escaping ([Get]) -> ()) {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else {return}
URLSession.shared.dataTask(with: url) { (data, _, _) in
let get = try! JSONDecoder().decode([Get].self, from: data!) //The error appears on this line - the ".decode" gets underlined as the source of the error
DispatchQueue.main.async {
completion(get)
}
}
.resume()
}
Lastly, here is the demo view I set up as a test to display the data:
struct apitestview: View {
#State var getRecipe: [Get] = []
var body: some View {
List(getRecipe) { get in
Text(get.body)
}
.onAppear() {
Api().getData { (get) in
self.getRecipe = get
}
}
}
Any thoughts? I have tried a few different variants of the code above, but I cannot seem to get to the bottom of the error.
Edits:
Here is a piece of the JSON data
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}
]
The fix was to add the missing pieces returned in the JSON object to my data model. See below:
struct Get: Codable, Identifiable {
var userId: Int //newly added
var id: Int //newly added
var title: String
var body: String
I can parse in my code json file like below. It works fine:
[
{
"albumId": 1,
"id": 1,
"title": "Accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952",
"publishDate": "2021-03-12"
},
{
"albumId": 1,
"id": 2,
"title": "Reprehenderit est deserunt velit ipsam",
"url": "https://via.placeholder.com/600/771796",
"thumbnailUrl": "https://via.placeholder.com/150/771796",
"publishDate": "2021-03-12"
}
]
but i need to update my json file to be able to present data from a specific parent. In this example: position1 or position 2.
{
"position1":[
{
"albumId": 1,
"id": 1,
"title": "Accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952",
"publishDate": "2021-03-12"
},
{
"albumId": 1,
"id": 2,
"title": "Reprehenderit est deserunt velit ipsam",
"url": "https://via.placeholder.com/600/771796",
"thumbnailUrl": "https://via.placeholder.com/150/771796",
"publishDate": "2021-03-12"
}
],
"position2":[
{
"albumId": 1,
"id": 1,
"title": "Accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952",
"publishDate": "2021-03-12"
},
{
"albumId": 1,
"id": 2,
"title": "Reprehenderit est deserunt velit ipsam",
"url": "https://via.placeholder.com/600/771796",
"thumbnailUrl": "https://via.placeholder.com/150/771796",
"publishDate": "2021-03-12"
}
]
}
My code looks like below. What should I do to list only children items from ex: position1.
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client
.get(Uri.parse('https://jsonplaceholder.typicode.com/photos'));
return compute(parsePhotos, response.body);
}
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
and
body: FutureBuilder<List<Photo>>(
future: fetchPhotos(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? PhotosList(photos: snapshot.data!)
: Center(child: CircularProgressIndicator());
},
),
I am writing an api to fetch data. I have three models Page , Section and Question.This is image of the erd diagram showing relationship between different entities .
I have defined there relationships in respective models.
Page Model
class CmsPage extends ActiveRecord
{
public static function tableName()
{
return '{{%cms_page}}';
}
public function getCmsSection()
{
/*Page and Section has many to many relation having a junction table*/
return $this->hasMany(CmsSection::className(),['id'=>'section_id'])->viaTable('tbl_cms_page_section',['page_id'=>'id']);
}
}
Section Model
class CmsSection extends ActiveRecord
{
public static function tableName()
{
return '{{%cms_section}}';
}
public function getCmsQuestion()
{
return $this->hasMany(CmsQuestion::className(),['id'=>'section_id']);
}
}
Question Model
class CmsQuestion extends ActiveRecord
{
public static function tableName()
{
return '{{%cms_question}}';
}
public function getCmsSection()
{
return $this->hasOne(CmsSection::className(),['section_id'=>'id']);
}
}
I want to fetch data as a json object like below
{
"id": "1",
"name": "Lorem Ipsom",
"title": "Eiusmod voluptate Lorem aute tempor fugiat eiusmod ex ipsum enim magna consequat cupidatat.",
"short_summary": "Will ContentsQuis consequat occaecat consequat aliquip adipisicing aute sunt pariatur culpa sint consectetur reprehenderit eu aliquip.",
"summary": "Officia eu fugiat quis laboris voluptate sunt sint cupidatat eu consequat et deserunt sint eu.",
"section": [
{
"id": 1,
"title": "Advanced Planning",
"short_summary": "Advanced Planning",
"summary": "Summary ",
"question": [
{
"id": 1,
"question_type_id": 1,
"show_relations": "true",
"title": "Family Members",
"place_holder_text": "Your faimly list is currently empty.",
"label_name": "Name",
"label_email": "Email",
"label_phone": "Mobile number",
"select_1": "url:test-data/dashboard-relationship.json",
"label": "Remarks"
},
{
"id": 2,
"question_type_id": 2,
"title": "Close Friends",
"place_holder_text": "Your list is close friends currently empty.",
"label_name": "Name",
"label_email": "Email",
"label_phone": "Mobile number",
"label_address": "Address",
"help_text": "<b>Close Friends<b><ul><li>1</</li><li>2</</li></ul>"
},
{
"id": 3,
"question_type_id": 3,
"title": "Designated Executors",
"place_holder_text": "It is vital you nominate an Executor",
"label_name": "Name",
"label_email": "Email",
"label_phone": "Mobile number",
"label_address": "Address"
},
{
"id": 4,
"question_type_id": 4,
"question_type": {},
"title": "Witnesses",
"place_holder_text": " It is vital you nominate an Executor",
"label_1": "Name",
"opption_2": "Email",
"label_3": "Phone",
"label_4": "Occupation",
"label": "Address"
}
]
},
{
"id": 2,
"title": "Labore proident cupidatat ex dolore occaecat in tempor sit proident sint labore minim cillum.",
"summary": "Dolor cupidatat consequat cillum deserunt laborum aliqua commodo occaecat sint aute cillum exercitation.",
"short_summary": "Ullamco Lorem incididunt dolore ipsum.",
"question": [
{
"id": 5,
"question_type_id": 5,
"title": "Last Words",
"short_summary": "Plan, the way you want!",
"summary": "Start by writing down.",
"label": "Write your last words here"
},
{
"id": 6,
"question_type_id": 5,
"title": "Venue",
"short_summary": "Plan, the way you want!",
"summary": "Start by writing down.",
"label": "Mention"
}
]
}
]
}
I have followed yii2 docs to come this far but not been able to get data in the json format. How to do that?
HI in API there a function call fields you can override that function :
Please check below code which will help you to get idea or for more detail
you read yii2 doc here
Yii 2 fields doc
public function fields()
{
return [
'id',
"name"
'title',
'short_summary',
'summary',
'section'=> function ($model) {
return $model->cmsSection;
},
];
}
if you want to go more nested then you can use array store first nested data and again use loop for inner data:
'section'=> function ($model) {
$sections = $model->cmsSection;
//store section data in array
//forloop of $sections
$sections->question;
//Again store question data in first array and return it
},
Aplly it you will understand what i am trying to tell you.
I am working a react blog app that list article and comment towards the article. I am using a JSON file to store data in the local.
I have added button to add new comment. I having trouble with adding the new comment to JSON data.
I have imported the data to my component file. I am stuck on how to update the JSON.
[{
"id": "5d403e5fbe39eb87471b8cd9",
"title": "laboris duis veniam",
"content": "Sint quis nisi tempor officia. occaecat pariatur sunt.\r\n",
"author":
{
"_id": "5d403e5f552ff12f1d0773d0",
"name": "Amanda Mckinney"
},
"comments": [
{
"id": "5d403e5f416a8a6b0447a069",
"content": "Do minim Culpa nostrud laborum consectet\r\n",
"commenter":
{
"_id": "5d403e5f58174caa22041e78",
"name": "Angelina Wong"
}
},
{
"id": "5d403e5f17475a36a4745241",
"content": "Velit reprehenderit et consectetur id in .\r\n",
"commenter":
{
"_id": "5d403e5f3511fa317d0bf561",
"name": "Gail Moss"
}
},
{
"id": "5d403e5f8419bad3767550b1",
"content": "Labore veniam dolor deserunt qui minim.\r\n",
"commenter":
{
"_id": "5d403e5f28bd1b5fc4d1be1b",
"name": "Staci Pierce"
}
},
{
"id": "5d403e5f43a52dd53b63f6c6",
"content": "Pariatur quis proident dolor veniam laborum.\r\n",
"commenter":
{
"_id": "5d403e5f33be38b996c4a8f1",
"name": "Mai Delaney"
}
},
{
"id": "5d403e5f9c53f6000ca12607",
"content": "Labore reprehenderit pariatur culpa non\r\n",
"commenter":
{
"_id": "5d403e5f1f77294e7fc77552",
"name": "Geraldine Gilliam"
}
}]
}]
In the comment session i want to add new comment object with details such as
{
"id": "5d403e5f9c53f6000ca12607",
"content": "Labore reprehenderit pariatur culpa non\r\n",
"commenter": {
"_id": "5d403e5f1f77294e7fc77552",
"name": "Geraldine Gilliam"
}
}
You can not write to a file of the machine in browser environment. You will have to use Node.js to achieve this.
I have json data structured in the following way from JsonPlaceholder API
'1': {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat",
"body": "quia et suscipit\nsuscipit"
}
I mapped the id as the key of the object and now want to return say objects '1' through '10' from the modified HTTP response shown above.
I tried using lodash _.pick():
_pick(object, ['1', '10']);
but that only returns object '1' and '10' instead of '1' through '10'
All help is appreciated thanks.
Have you considered just putting them in an array and then filtering it?
let data = [
{ id: 1 }, { id: 2 }, { id: 11 }
];
let filtered = data.filter(e => { return e.id >= 1 && e.id <= 10 });
console.dir(data);
console.dir(filtered);
if you can't and are stuck with them in a JSON object, maybe something like this that extracts the values first:
let json = {
'1': {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat",
"body": "quia et suscipit\nsuscipit"
},
'10': {
"userId": 10,
"id": 10,
"title": "sunt aut facere repellat",
"body": "quia et suscipit\nsuscipit"
},
'11': {
"userId": 11,
"id": 11,
"title": "sunt aut facere repellat",
"body": "quia et suscipit\nsuscipit"
}
};
var filtered =
Object
.keys(json).map(key => json[key])
.filter(val => val.id >= 1 && val.id <= 10);
console.dir(json);
console.dir(filtered);
Since you are already using lodash why not just use range to create an array of integers and then map over that too convert them to strings.
_.pick(object, _.range(1,10).map(_.toString));