How to Create Nested Json Using ArduinoJson on ESP8266 - json

I want this Output Json From Esp8266
I am trying with another json lib https://github.com/arduino-libraries/Arduino_JSON
this is lightweight library than arduinojson.org
{
"ID": "0785E7",
"DEVICE": "SINGLE_RELAY",
"Public_Name": "Demo Switch",
"version": 1,
"payloadVersion": 1,
"SW": 1,
"HW": 1,
"CHIPSIZE": 1048576,
"CHIPSPEED": 40000000,
"CHIPMODE": 3,
"capabilities": [
{
"interface": "Demo.Switch",
"type": "ONOFF",
"version": "1.0",
"sync": true,
"control_pin": 2,
"MQTT_SWITCH_TOPIC": "on",
"MQTT_SWITCH_SYNC": "sync"
},
{
"interface": "Demo.Countdown",
"type": "Countdown",
"version": "1.0",
"sync": true,
"control_pin": 2,
"MQTT_SWITCH_TOPIC": "s",
"MQTT_SWITCH_SYNC": "x"
},
{
"interface": "Demo.Schedule",
"type": "Schedule",
"version": "1.0",
"sync": true,
"control_pin": 2,
"MQTT_SWITCH_TOPIC": "s",
"MQTT_SWITCH_SYNC": "x"
}
]
}
Arduino Function
String Device_info()
{
JSONVar json;
json["ID"] = ESPID;
json["DEVICE"] = DEVICE_TYPE;
json["Public_Name"] = DEVICE_CHANNEL;
json["version"] = relaystatus1;
json["payloadVersion"] = RelayPIN;
json["SW"] = userid;
json["HW"] = Trigger;
json["CHIPSIZE"] = rssi_str;
json["CHIPSPEED"] = "1";;
String jsonString = JSON.stringify(json);
}
i want to add "capabilities" objectArray in this Like Above json.

The createNestedObject() method can be used to create the capabilities objects inside a nested array.
The ArduinoJson Assistant suggests the following code:
const size_t capacity =
JSON_ARRAY_SIZE(3) + 3*JSON_OBJECT_SIZE(7) + JSON_OBJECT_SIZE(11);
DynamicJsonDocument doc(capacity);
doc["ID"] = "0785E7";
doc["DEVICE"] = "SINGLE_RELAY";
doc["Public_Name"] = "Demo Switch";
doc["version"] = 1;
doc["payloadVersion"] = 1;
doc["SW"] = 1;
doc["HW"] = 1;
doc["CHIPSIZE"] = 1048576;
doc["CHIPSPEED"] = 40000000;
doc["CHIPMODE"] = 3;
JsonArray capabilities = doc.createNestedArray("capabilities");
JsonObject capabilities_0 = capabilities.createNestedObject();
capabilities_0["interface"] = "Demo.Switch";
capabilities_0["type"] = "ONOFF";
capabilities_0["version"] = "1.0";
capabilities_0["sync"] = true;
capabilities_0["control_pin"] = 2;
capabilities_0["MQTT_SWITCH_TOPIC"] = "on";
capabilities_0["MQTT_SWITCH_SYNC"] = "sync";
JsonObject capabilities_1 = capabilities.createNestedObject();
capabilities_1["interface"] = "Demo.Countdown";
capabilities_1["type"] = "Countdown";
capabilities_1["version"] = "1.0";
capabilities_1["sync"] = true;
capabilities_1["control_pin"] = 2;
capabilities_1["MQTT_SWITCH_TOPIC"] = "s";
capabilities_1["MQTT_SWITCH_SYNC"] = "x";
JsonObject capabilities_2 = capabilities.createNestedObject();
capabilities_2["interface"] = "Demo.Schedule";
capabilities_2["type"] = "Schedule";
capabilities_2["version"] = "1.0";
capabilities_2["sync"] = true;
capabilities_2["control_pin"] = 2;
capabilities_2["MQTT_SWITCH_TOPIC"] = "s";
capabilities_2["MQTT_SWITCH_SYNC"] = "x";
serializeJson(doc, Serial);

JSONVar supported;
JSONVar Countdown;
Countdown["interface"] = interface_countdown;
Countdown["type"] = interface_countdown_type;
Countdown["version"] = version_1;
Countdown["retrievable"] = true;
Countdown["MIN_COUNT"] = 1;
Countdown["MAX_COUNT"] = COUNTDOWNCOUNT;
Countdown["control_pin"] = RELAY_PIN;
Countdown["MQTT_TOPIC"] = MQTT_COUNTDOWN_IN;
Countdown["MQTT_SYNC"] = MQTT_COUNTDOWN_IN;
JSONVar schedule;
schedule["interface"] = interface_Schedule;
schedule["type"] = interface_Schedule_type;
schedule["version"] = version_1;
schedule["retrievable"] = true;
schedule["control_pin"] = RELAY_PIN;
schedule["MIN_COUNT"] = 1;
schedule["MAX_COUNT"] = SCHEDUECOUNT;
schedule["MQTT_TOPIC"] = MQTT_TIMMER_IN;
schedule["MQTT_SYNC"] = MQTT_TIMMER_IN;
supported[0] = Countdown;
supported[1] = schedule;
JSONVar power_control;
power_control["interface"] = interface_power;
power_control["type"] = interface_power_type;
power_control["version"] = version_1;
power_control["retrievable"] = true;
power_control["proactivelyReported"] = true;
power_control["control_pin"] = RELAY_PIN;
power_control["MQTT_SWITCH_TOPIC"] = MQTT_SWITCH_COMMAND_TOPIC1;
power_control["MQTT_SWITCH_SYNC"] = MQTT_SWITCH_PUBLISH_TOPIC1;
power_control["supported"] = supported;
JSONVar capabilities;
capabilities[0] = power_control;
delay(200);
JSONVar json;
json["ID"] = ESPID;
json["DEVICE"] = DEVICE_TYPE;
json["MACADDRESS"] = String(WiFi.macAddress());
json["Public_Name"] = DEVICE_CHANNEL;
json["version"] = version_1;
json["payloadVersion"] = payloadVersion;
json["SW"] = SW;
json["HW"] = HW;
json["CHIPSIZE"] = (int)ESP.getFlashChipRealSize();
json["CHIPSPEED"] = (int)ESP.getFlashChipSpeed();
json["capabilities"] = capabilities;
delay(200);
String jsonString = JSON.stringify(json);
Serial.println(jsonString);

Related

Get array item by 1-indexed value in another field

The Firefox file sessionstore-backups/recovery.jsonlz4 contains information about the current Firefox windows in (compressed) JSON format. This is a simplified format representative of that file:
{
"index": 2,
"entries": [
{
"title": "Foo bar 0",
"url": "https://example.com/bar"
},
{
"title": "Foo bar 1",
"url": "https://example.com/bar"
},
{
"title": "Foo bar 2",
"url": "https://example.com/bar"
}
]
}
The index field represents the currently-displayed history item per tab. Being 1-indexed, in the example above it represents the "Foo bar 1" entry.
How can I use that value in jq to get that tab?
For testing on your own system, the following bash line will get you to this point on most modern Linux systems:
lz4jsoncat ~/.mozilla/firefox/t6e99qbe.default-release/sessionstore-backups/recovery.jsonlz4 | jq '.windows[0].tabs' | jq 'sort_by(.lastAccessed)[-1]'
This returns the most recent tab, but with all history items in the entries array. As the user could have navigated back in the history, we need the index value to determine which entry to return. Piped through gron, it looks like this:
json = {};
json.attributes = {};
json.entries = [];
json.entries[0] = {};
json.entries[0].ID = 504;
json.entries[0].cacheKey = 0;
json.entries[0].docIdentifier = 586;
json.entries[0].docshellUUID = "{b6c1e18a-d0f5-4ba2-996e-ddd9fc28322a}";
json.entries[0].hasUserInteraction = true;
json.entries[0].persist = true;
json.entries[0].principalToInherit_base64 = "eyIxIjp7IjAiOiJtb3otZXh0ZW5zaW9uOi8vOTAzYWU2NDgtMzRlNi00NGQ3LTg0NjYtYzgxMWQyMTg2YjBkLyJ9fQ==";
json.entries[0].resultPrincipalURI = null;
json.entries[0].title = "Tridactyl Top Tips & New Tab Page";
json.entries[0].triggeringPrincipal_base64 = "eyIxIjp7IjAiOiJtb3otZXh0ZW5zaW9uOi8vOTAzYWU2NDgtMzRlNi00NGQ3LTg0NjYtYzgxMWQyMTg2YjBkLyJ9fQ==";
json.entries[0].url = "moz-extension://7ba85bcd-8d63-4e74-a723-e627a31d6274/static/newtab.html";
json.entries[1] = {};
json.entries[1].ID = 506;
json.entries[1].cacheKey = 0;
json.entries[1].docIdentifier = 588;
json.entries[1].docshellUUID = "{b6c1e18a-d0f5-4ba2-996e-ddd9fc28322a}";
json.entries[1].hasUserInteraction = true;
json.entries[1].persist = true;
json.entries[1].referrerInfo = "BBoSnxDOS9qmDeAnom1e0AAAAAAAAAAAwAAAAAAAAEYAAAAAAAEBAAAAAAEA";
json.entries[1].resultPrincipalURI = null;
json.entries[1].title = "Stack Overflow - Where Developers Learn, Share, & Build Careers";
json.entries[1].triggeringPrincipal_base64 = "eyIzIjp7fX0=";
json.entries[1].url = "https://stackoverflow.com/";
json.entries[2] = {};
json.entries[2].ID = 508;
json.entries[2].cacheKey = 0;
json.entries[2].csp = "CdntGuXUQAS/4CfOuSPZrAAAAAAAAAAAwAAAAAAAAEYB3pRy0IA0EdOTmQAQS6D9QJIHOlRteE8wkTq4cYEyCMYAAAAC/////wAAAbsBAAAAGmh0dHBzOi8vc3RhY2tvdmVyZmxvdy5jb20vAAAAAAAAAAUAAAAIAAAAEQAAAAj/////AAAACP////8AAAAIAAAAEQAAABkAAAABAAAAGQAAAAEAAAAZAAAAAQAAABoAAAAAAAAAGv////8AAAAA/////wAAABn/////AAAAGf////8BAAAAAAAAAAAAKHsiMSI6eyIwIjoiaHR0cHM6Ly9zdGFja292ZXJmbG93LmNvbS8ifX0AAAABAAAASwB1AHAAZwByAGEAZABlAC0AaQBuAHMAZQBjAHUAcgBlAC0AcgBlAHEAdQBlAHMAdABzADsAIABmAHIAYQBtAGUALQBhAG4AYwBlAHMAdABvAHIAcwAgACcAcwBlAGwAZgAnACAAaAB0AHQAcABzADoALwAvAHMAdABhAGMAawBlAHgAYwBoAGEAbgBnAGUALgBjAG8AbQAA";
json.entries[2].docIdentifier = 590;
json.entries[2].docshellUUID = "{b6c1e18a-d0f5-4ba2-996e-ddd9fc28322a}";
json.entries[2].hasUserInteraction = true;
json.entries[2].persist = true;
json.entries[2].principalToInherit_base64 = "eyIxIjp7IjAiOiJodHRwczovL3N0YWNrb3ZlcmZsb3cuY29tLyJ9fQ==";
json.entries[2].referrerInfo = "BBoSnxDOS9qmDeAnom1e0AAAAAAAAAAAwAAAAAAAAEYBAAAAGmh0dHBzOi8vc3RhY2tvdmVyZmxvdy5jb20vAAAACAEBAAAAGmh0dHBzOi8vc3RhY2tvdmVyZmxvdy5jb20vAQE=";
json.entries[2].resultPrincipalURI = null;
json.entries[2].title = "Highest scored questions - Stack Overflow";
json.entries[2].triggeringPrincipal_base64 = "eyIxIjp7IjAiOiJodHRwczovL3N0YWNrb3ZlcmZsb3cuY29tLyJ9fQ==";
json.entries[2].url = "https://stackoverflow.com/questions";
json.entries[3] = {};
json.entries[3].ID = 510;
json.entries[3].cacheKey = 0;
json.entries[3].csp = "CdntGuXUQAS/4CfOuSPZrAAAAAAAAAAAwAAAAAAAAEYB3pRy0IA0EdOTmQAQS6D9QJIHOlRteE8wkTq4cYEyCMYAAAAC/////wAAAbsBAAAAI2h0dHBzOi8vc3RhY2tvdmVyZmxvdy5jb20vcXVlc3Rpb25zAAAAAAAAAAUAAAAIAAAAEQAAAAj/////AAAACP////8AAAAIAAAAEQAAABkAAAAKAAAAGQAAAAoAAAAZAAAAAQAAABoAAAAJAAAAGv////8AAAAA/////wAAABn/////AAAAGf////8BAAAAAAAAAAAAMXsiMSI6eyIwIjoiaHR0cHM6Ly9zdGFja292ZXJmbG93LmNvbS9xdWVzdGlvbnMifX0AAAABAAAASwB1AHAAZwByAGEAZABlAC0AaQBuAHMAZQBjAHUAcgBlAC0AcgBlAHEAdQBlAHMAdABzADsAIABmAHIAYQBtAGUALQBhAG4AYwBlAHMAdABvAHIAcwAgACcAcwBlAGwAZgAnACAAaAB0AHQAcABzADoALwAvAHMAdABhAGMAawBlAHgAYwBoAGEAbgBnAGUALgBjAG8AbQAA";
json.entries[3].docIdentifier = 592;
json.entries[3].docshellUUID = "{b6c1e18a-d0f5-4ba2-996e-ddd9fc28322a}";
json.entries[3].hasUserInteraction = true;
json.entries[3].persist = true;
json.entries[3].principalToInherit_base64 = "eyIxIjp7IjAiOiJodHRwczovL3N0YWNrb3ZlcmZsb3cuY29tL3F1ZXN0aW9ucyJ9fQ==";
json.entries[3].referrerInfo = "BBoSnxDOS9qmDeAnom1e0AAAAAAAAAAAwAAAAAAAAEYBAAAAI2h0dHBzOi8vc3RhY2tvdmVyZmxvdy5jb20vcXVlc3Rpb25zAAAACAEBAAAAI2h0dHBzOi8vc3RhY2tvdmVyZmxvdy5jb20vcXVlc3Rpb25zAQE=";
json.entries[3].resultPrincipalURI = null;
json.entries[3].title = "Tags - Stack Overflow";
json.entries[3].triggeringPrincipal_base64 = "eyIxIjp7IjAiOiJodHRwczovL3N0YWNrb3ZlcmZsb3cuY29tL3F1ZXN0aW9ucyJ9fQ==";
json.entries[3].url = "https://stackoverflow.com/tags";
json.entries[4] = {};
json.entries[4].ID = 512;
json.entries[4].cacheKey = 0;
json.entries[4].csp = "CdntGuXUQAS/4CfOuSPZrAAAAAAAAAAAwAAAAAAAAEYB3pRy0IA0EdOTmQAQS6D9QJIHOlRteE8wkTq4cYEyCMYAAAAC/////wAAAbsBAAAAHmh0dHBzOi8vc3RhY2tvdmVyZmxvdy5jb20vdGFncwAAAAAAAAAFAAAACAAAABEAAAAI/////wAAAAj/////AAAACAAAABEAAAAZAAAABQAAABkAAAAFAAAAGQAAAAEAAAAaAAAABAAAABr/////AAAAAP////8AAAAZ/////wAAABn/////AQAAAAAAAAAAACx7IjEiOnsiMCI6Imh0dHBzOi8vc3RhY2tvdmVyZmxvdy5jb20vdGFncyJ9fQAAAAEAAABLAHUAcABnAHIAYQBkAGUALQBpAG4AcwBlAGMAdQByAGUALQByAGUAcQB1AGUAcwB0AHMAOwAgAGYAcgBhAG0AZQAtAGEAbgBjAGUAcwB0AG8AcgBzACAAJwBzAGUAbABmACcAIABoAHQAdABwAHMAOgAvAC8AcwB0AGEAYwBrAGUAeABjAGgAYQBuAGcAZQAuAGMAbwBtAAA=";
json.entries[4].docIdentifier = 594;
json.entries[4].docshellUUID = "{b6c1e18a-d0f5-4ba2-996e-ddd9fc28322a}";
json.entries[4].hasUserInteraction = false;
json.entries[4].persist = true;
json.entries[4].principalToInherit_base64 = "eyIxIjp7IjAiOiJodHRwczovL3N0YWNrb3ZlcmZsb3cuY29tL3RhZ3MifX0=";
json.entries[4].referrerInfo = "BBoSnxDOS9qmDeAnom1e0AAAAAAAAAAAwAAAAAAAAEYBAAAAHmh0dHBzOi8vc3RhY2tvdmVyZmxvdy5jb20vdGFncwAAAAgBAQAAAB5odHRwczovL3N0YWNrb3ZlcmZsb3cuY29tL3RhZ3MBAQ==";
json.entries[4].resultPrincipalURI = null;
json.entries[4].title = "Users - Stack Overflow";
json.entries[4].triggeringPrincipal_base64 = "eyIxIjp7IjAiOiJodHRwczovL3N0YWNrb3ZlcmZsb3cuY29tL3RhZ3MifX0=";
json.entries[4].url = "https://stackoverflow.com/users";
json.hidden = false;
json.index = 3;
json.lastAccessed = 1651407567904;
json.requestedIndex = 0;
json.searchMode = null;
json.userContextId = 0
Just index entries by index minus one?
.entries[.index - 1]
Online demo
The last item in entries is not necessarily the tab that was opened. [.index - 1] only works if user_pref("browser.sessionstore.max_serialize_forward", 0); cf. https://wiki.mozilla.org/Firefox/session_restore#Browser_settings

Parsing JSON values from media file metadata on OSX

This is my very first attempt at Swift 3 and Xcode 8.3.3. I'm trying to parse a JSON metadata extracted from a file through the command-line application Exiftool.
let task = Process()
let filePath = url.path
let etPath = "/usr/local/bin/exiftool"
task.launchPath = etPath
task.arguments = ["-a", "-g1", "-json", filePath]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
// Get the data
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
let mydata = output?.data(using: String.Encoding.utf8.rawValue)!
do {
let myJson = try JSONSerialization.jsonObject(with: mydata!, options: []) as AnyObject
if let XMPdc = myJson["XMP-dc"] as AnyObject? {
if let creator = XMPdc["Creator"] as! NSArray? {
print(creator)
}
}
} catch let error as NSError {
print(error)
}
The first part of the script works well, allowing me to get the JSON data into the variable myJson. If I print that variable out, I obtain this:
(
{
Composite = {
ImageSize = 100x100;
Megapixels = "0.01";
};
ExifIFD = {
ColorSpace = Uncalibrated;
ExifImageHeight = 100;
ExifImageWidth = 100;
};
ExifTool = {
ExifToolVersion = "10.61";
};
File = {
ExifByteOrder = "Little-endian (Intel, II)";
FileType = TIFF;
FileTypeExtension = tif;
MIMEType = "image/tiff";
};
"ICC-header" = {
CMMFlags = "Not Embedded, Independent";
ColorSpaceData = "RGB ";
ConnectionSpaceIlluminant = "0.9642 1 0.82487";
DeviceAttributes = "Reflective, Glossy, Positive, Color";
DeviceManufacturer = KODA;
DeviceModel = ROMM;
PrimaryPlatform = "Microsoft Corporation";
ProfileCMMType = KCMS;
ProfileClass = "Display Device Profile";
ProfileConnectionSpace = "XYZ ";
ProfileCreator = KODA;
ProfileDateTime = "1998:12:01 18:58:21";
ProfileFileSignature = acsp;
ProfileID = 0;
ProfileVersion = "2.1.0";
RenderingIntent = "Media-Relative Colorimetric";
};
"ICC_Profile" = {
BlueMatrixColumn = "0.03134 9e-05 0.82491";
BlueTRC = "(Binary data 14 bytes, use -b option to extract)";
DeviceMfgDesc = KODAK;
DeviceModelDesc = "Reference Output Medium Metric(ROMM) ";
GreenMatrixColumn = "0.13519 0.71188 0";
GreenTRC = "(Binary data 14 bytes, use -b option to extract)";
MakeAndModel = "(Binary data 40 bytes, use -b option to extract)";
MediaWhitePoint = "0.9642 1 0.82489";
ProfileCopyright = "Copyright (c) Eastman Kodak Company, 1999, all rights reserved.";
ProfileDescription = "ProPhoto RGB";
RedMatrixColumn = "0.79767 0.28804 0";
RedTRC = "(Binary data 14 bytes, use -b option to extract)";
};
IFD0 = {
Artist = Autore;
BitsPerSample = "16 16 16";
Compression = LZW;
ImageDescription = "Creator: Test ; Date: 1900";
ImageHeight = 100;
ImageWidth = 100;
ModifyDate = "2017:08:10 10:58:42";
Orientation = "Horizontal (normal)";
PhotometricInterpretation = RGB;
PlanarConfiguration = Chunky;
ResolutionUnit = inches;
RowsPerStrip = 100;
SamplesPerPixel = 3;
Software = "Adobe Photoshop CC 2015 (Macintosh)";
StripByteCounts = 1037;
StripOffsets = 11450;
SubfileType = "Full-resolution Image";
XResolution = 300;
YCbCrPositioning = "Co-sited";
YResolution = 300;
};
Photoshop = {
DisplayedUnitsX = inches;
DisplayedUnitsY = inches;
GlobalAltitude = 30;
GlobalAngle = 90;
HasRealMergedData = Yes;
IPTCDigest = 00000000000000000000000000000000;
PhotoshopThumbnail = "(Binary data 557 bytes, use -b option to extract)";
PixelAspectRatio = 1;
PrintPosition = "0 0";
PrintScale = 1;
PrintStyle = Centered;
ReaderName = "Adobe Photoshop CC 2015";
SlicesGroupName = "";
"URL_List" = (
);
WriterName = "Adobe Photoshop";
XResolution = 300;
YResolution = 300;
};
"XMP-dc" = {
Creator = Autore;
Description = "Creator: Test ; Date: 1900";
Format = "image/tiff";
Publisher = "-";
Rights = "-";
Subject = "-";
Title = tite;
};
"XMP-pdf" = {
Producer = "-";
};
"XMP-photoshop" = {
ColorMode = RGB;
ICCProfileName = "ProPhoto RGB";
};
"XMP-x" = {
XMPToolkit = "Image::ExifTool 10.53";
};
"XMP-xmp" = {
CreateDate = 1900;
CreatorTool = "Adobe Photoshop CC 2015 (Macintosh)";
MetadataDate = "2017:08:10 10:58:42-04:00";
ModifyDate = "2017:08:10 10:58:42-04:00";
ThumbnailFormat = "-";
ThumbnailImage = "(Binary data 48 bytes, use -b option to extract)";
};
"XMP-xmpRights" = {
Marked = 1;
};
}
)
However, I don't understand how to correctly parse the data in order to store a specific value, let's say the value that corresponds to the object { "XMP-dc" = {Creator = Autore } }, within my variable creator.
What am I doing wrong?
Try to downcast your json and xmp-dc to the dictionary
let myJson = try JSONSerialization.jsonObject(with: mydata!, options: []) as? [String: Any]
if let XMPdc = myJson?["XMP-dc"] as? [String: Any?] {
//print that dictionary to be sure that al is correct
print(XMPdc)
//I'm not sure that the value Creator is an Array, honestly I don't understand what is the type of that object, but anyway, few fixes for your code
if let creator = XMPdc["Creator"] as? NSArray {
print(creator)
}
}
Again, I'm not sure about the type of the variable Creator, but at least you will know this when you will make print(XMPdc), then you can change the downcast for the creator to the String or whatever.
Let me know if you need something

Laravel nesting json response

i want to create json like this my json in my api controller in laravel.
here the controller
$data = [];
foreach ($products as $p => $product) {
$components = [];
$product_obj = new StdClass();
$product_obj->id = $product->id;
$product_obj->name = $product->name;
$product_obj->category_id = $product->category_id;
//$product_obj->category_name = $product->category->name;
$product_obj->sku = $product->sku;
$product_obj->weight = $product->weight;
$product_obj->discount_type = $product->discount_type;
$product_obj->additional_price = $product->additional_price;
$product_obj->discount = $product->discount;
$product_obj->start_discount = $date_start;
$product_obj->end_discount = $date_end;
$product_obj->thumbnail = $product->thumbnail;
$product_obj->mime_content_type = $product->mime_content_type;
$product_obj->description = $product->description;
$product_obj->is_active = $product->is_active;
//$product_obj->created_at = $product->created_at;
//$product_obj->updated_at = $product->updated_at;
foreach ($product->components()->get() as $c => $component) {
$item_arr = [];
$component_obj = new StdClass();
$component_obj->id = $component->id;
$component_obj->product_id = $component->product_id;
$component_obj->item_id = $component->item_id;
$component_obj->quantity = $component->quantity;
$component_obj->is_mandatory = $component->is_mandatory;
$component_obj->is_customqty = $component->is_customqty;
//$component_obj->created_at = $component->created_at;
//$component_obj->updated_at = $component->updated_at;
$component_obj->quantity_step = $component->quantity_step;
$component_obj->display_order = $component->display_order;
$component_obj->quantity_display = $component->quantity_display;
$component_obj->default_template = $component->default_template;
foreach ($component->item()->get() as $i => $item) {
$item_option_groups = [];
//$options = [];
$item_templates = [];
$item_backgrounds = [];
$item_background_images = [];
$item_obj = new StdClass();
$item_obj->id = $item->id;
$item_obj->name = $item->name;
$item_obj->price = $item->price;
$item_obj->width = $item->width;
$item_obj->height = $item->height;
$item_obj->allow_image_upload = $item->allow_image_upload;
foreach ($item->itemOptionGroups()->get() as $iog => $item_option_groups) {
$item_option_groups = [];
$item_option_groups_obj = new StdClass();
$item_option_groups_obj->id = $item_option_groups->id;
$item_option_groups_obj->name = $item_option_groups->name;
//miising item option on databse
foreach ($item->options()->get() as $io => $item_options) {
$option = [];
$item_options_obj = new StdClass();
$item_options_obj->id = $item_options->id;
$item_options_obj->item_id = $item_options->item_id;
$item_options_obj->item_group_id = $item_options->item_group_id;
$item_options_obj->option_id = $item_options->option_id;
foreach ($item->option()->get() as $o => $item_options) {
$option_obj = new StdClass();
$option_obj->id = $option->id;
$option_obj->name = $option->name;
$option_obj->price = $option->price;
$option[] = $option_obj;
}
$item_options_obj->option = $item_options->option;
$item_options[] = $item_options_obj;
}
$item_option_groups_obj->item_option_group = $item_option_groups;
$item_option_groups[] = $item_option_groups_obj;
//$component_obj->item = $item_arr;
//$components[] = $component_obj;
}
foreach ($item->itemTemplates()->get() as $it => $item_templates) {
$template = [];
$item_templates_obj = new StdClass();
$item_templates_obj->id = $item_templates->id;
$item_templates_obj->template_id = $item_templates->template_id;
$item_templates_obj->item_id = $item_templates->item_id;
foreach ($item->template()->get() as $t => $template) {
$template_obj = new StdClass();
$template_obj->id = $template->id;
$template_obj->name = $template->name;
$template_obj->row = $template->row;
$template_obj->col = $template->col;
$template_obj->thumbnail = $template->thumbnail;
$template_obj->margin = $template->margin;
$template_obj->padding = $template->padding;
$template[] = $template_obj;
}
$item_templates_obj->template = $template;
$item_templates[] = $item_templates_obj;
}
foreach ($item->itemBackgrounds()->get() as $ib => $item_backgrounds) {
$background_color = [];
$item_backgrounds_obj = new StdClass();
$item_backgrounds_obj->id = $item_backgrounds->id;
$item_backgrounds_obj->item_id = $item_backgrounds->item_id;
$item_backgrounds_obj->background_color_id = $item_backgrounds->background_color_id;
foreach ($item->background_color()->get() as $bc => $background_color) {
$background_color_obj = new StdClass();
$background_color_obj->id = $background_color->id;
$background_color_obj->color = $background_color->color;
$background_color[] = $background_color_obj;
}
$item_backgrounds_obj->background_color = $background_color;
$item_backgrounds[] = $item_backgrounds_obj;
}
foreach ($item->itemBackgroundImages()->get() as $ibi => $item_background_images) {
$background_image = [];
$item_background_images_obj = new StdClass();
$item_background_images_obj->id = $item_background_images->id;
$item_background_images_obj->item_id = $item_background_images->item_id;
$item_background_images_obj->background_image_id = $item_background_images->background_image_id;
foreach ($item->background_image()->get() as $bi => $background_image) {
$background_image_obj = new StdClass();
$background_image_obj->id = $background_image->id;
$background_image_obj->image = $background_image->image;
$background_image[] = $background_image_obj;
}
$item_background_images_obj->background_image = $background_image;
$item_background_images[] = $item_background_images_obj;
}
$item_obj->item_option_groups = $item_option_groups;
//$item_obj->item_option_groups = $options;
$item_obj->item_templates = $item_templates;
$item_obj->item_backgrounds = $item_backgrounds;
$item_obj->item_background_images = $item_background_images;
$item_arr[] = $item_obj;
}
$component_obj->item = $item_arr;
$components[] = $component_obj;
}
$product_obj->product_components = $components;
$data[] = $product_obj;
}
if(count($data) == 1){
$data = $data[0];
}
return response()->json($data);
}
}
and this is what i get from this controller json can anyone solve my this ? looks like the nesting going wrong. please help.
About json responses, you could use Laravel's built-in JSON response for this.
So, instead of building the json fields yourself, let laravel do it for you, like this:
return \Response::json( /* Array||Object to be converted */ );
//or
return response()->json( /* Array||Object to be converted */ );
And about the nested relationships that might not be loaded. Assuming that 'products', and 'items...' are Models:
I think a good way would be to use the 'with' or 'load' methods from your model, like this:
$products->load('components');
If you need multiple nested relationships, you can use the 'dot notation' like described in this question
Hope it helps.
Laravel response function automatically convert an array to JSON.
For example in my controller i have following:
$return_data = array('data' => 'some data','response' => 1);
return response($return_data);
Also The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function:
return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]);
For more details you can visit: https://laravel.com/docs/5.1/responses#json-responses

How to remove {"Result": in JSON string?

I have the following JSON result when calling an API, how can I convert the JSON string I have so I can just see the results:
var response = request_.responseText;
var obj = JSON.parse(request_.response);
var j = obj;
var js = JSON.stringify(j)
console.log(js)
JSON Output of var js:
{"Result":[{"PK_ID":1,"MedicationId":1,"NHS_Number":"123","Medication_Name":"Asprin","Read_Code":"XaaYI","Dose":"500mg","Date_Started":"02/06/2016","Date_Ended":"03/06/2016"},{"PK_ID":2,"MedicationId":2,"NHS_Number":"1234","Medication_Name":"Ibuprofen","Read_Code":"EtQWEl","Dose":"100mg","Date_Started":"03/02/2016","Date_Ended":"05/02/2016"}]}
How can I remove the {"Result": } code that is wrapped around my JSON?
Update from
var j = obj;
to
var j = obj.Result;
var obj = {
"Result": [{
"PK_ID": 1,
"MedicationId": 1,
"NHS_Number": "123",
"Medication_Name": "Asprin",
"Read_Code": "XaaYI",
"Dose": "500mg",
"Date_Started": "02/06/2016",
"Date_Ended": "03/06/2016"
}, {
"PK_ID": 2,
"MedicationId": 2,
"NHS_Number": "1234",
"Medication_Name": "Ibuprofen",
"Read_Code": "EtQWEl",
"Dose": "100mg",
"Date_Started": "03/02/2016",
"Date_Ended": "05/02/2016"
}]
};
var j = obj.Result;
var js = JSON.stringify(j);
console.log(js);

How to add required attendees in appoitment in microsoft crm

I added a new contact in microsoft dynamics 4.0 from C#. How to required attendees from code? I created a contact like this. now how to add this contact as required attendees for selected appointment ?
CRM.CrmService service = GetService();
var contactResult = new contact
{
emailaddress1 = userContact.Email
};
var requestContact = new RetrieveDuplicatesRequest
{
BusinessEntity = contactResult
,
MatchingEntityName = EntityName.contact.ToString()
,
PagingInfo = new PagingInfo
{
PageNumber = 1,
Count = 1
}
};
bool blnEmailExists = false;
try
{
var response = (RetrieveDuplicatesResponse)
service.Execute(requestContact);
foreach (contact contactItem in response.DuplicateCollection.BusinessEntities)
{
blnEmailExists = true;
contactResult.contactid = new Key();
contactResult.contactid.Value = new Guid(contactItem.contactid.Value.ToString());
contactResult.firstname = userContact.FirstName;
contactResult.lastname = userContact.LastName;
contactResult.fullname = userContact.FullName;
contactResult.mobilephone = userContact.PhoneNumber;
contactResult.description = userContact.Description;
service.Update(contactResult);
}
if (!blnEmailExists)
{
contactResult.firstname = userContact.FirstName;
contactResult.lastname = userContact.LastName;
contactResult.fullname = userContact.FullName;
contactResult.mobilephone = userContact.PhoneNumber;
contactResult.description = userContact.Description;
Guid contactId = service.Create(contactResult);
if (!string.IsNullOrEmpty(userContact.Notes))
AppendToNotesSection(userContact.Notes, contactId, service);
}
}
catch (System.Web.Services.Protocols.SoapException ex)
{
throw new Exception(ex.Message);
}
Thanks
Through activityParty it can be updated, atlast i found it and fixed.
CRM.CrmService service = GetService();
appointment appointment = (appointment)service.Retrieve(EntityName.appointment.ToString(), activityid, new AllColumns());
if(appointment == null)
{
throw new ArgumentNullException("Invalid Appointment");
}
contact contact = RegisterContact(userContact, service);
activityparty[] activityParty = new activityparty[appointment.requiredattendees.Length + 1];
activityParty[0] = new activityparty();
activityParty[0].partyid = new Lookup();
activityParty[0].partyid.Value = contact.contactid.Value;
activityParty[0].partyid.type = "contact";
Int16 index = 1;
foreach (var item in appointment.requiredattendees)
{
//for avoiding duplicates
if (item.partyid.Value != contact.contactid.Value)
{
activityParty[index] = new activityparty();
activityParty[index].partyid = item.partyid;
activityParty[index].partyid.Value = item.partyid.Value;
activityParty[index].partyid.type = item.partyid.type;
index++;
}
}
appointment.requiredattendees = activityParty;
try
{
service.Update(appointment);
}
catch (System.Web.Services.Protocols.SoapException ex)
{
Console.WriteLine(ex.Message + ". " + ex.Detail.InnerText);
}