I am trying to filter JSON data with my Arduin (working with an ESP8266).
This is what I have :
if (httpCode > 0) {
// Parsing
const size_t bufferSize = JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(8) + 370;
DynamicJsonBuffer jsonBuffer(bufferSize);
JsonObject& root = jsonBuffer.parseObject(http.getString());
// Parameters
int id = root["Reismogelijkheid"];
const char* departure = root["ActueleVertrekTijd"];
// Output to serial monitor
Serial.print("Vertrijktijd:");
Serial.println(departure);
}
I can make connection to my wifi network and I can make connection to the website to get JSON data from here : http://hendriks.pm/ns.php but I want to filter the data and only get the ActueleVertrekTijd, so that I can store it in a const and that I can see it on my Serial monitor.
I tried to use this example : https://www.instructables.com/id/ESP8266-Parsing-JSON/ but that didn't worked for me.
This is the Json :
Hello and welcome to Stackoverflow,
The problem is that you dont traverse trough the JSON.
If you want to retreive a value of an Object you should use
root["Reismogelijkheid"]["ActueleVertrekTijd"]
or if it is consistent:
root["Reismogelijkheid"][5]
instead of
root["Reismogelijkheid"]
This will give you the value that you want.
EDIT
For more information about parsing JSON you can use this site:
https://randomnerdtutorials.com/decoding-and-encoding-json-with-arduino-or-esp8266/
Related
I'm working on a Photoshop CES extension and attempting to encrypt data using CryptoJS. This all works, except when I convert the encrypted data to a string and then try to decrypt it.
Here's a link to a JS Fiddle that works:
https://jsfiddle.net/davevsdave/atwpbmr5/3/
This same code in ExtendScript Toolkit or running in Photoshop does not return the correct finalResult var. Here's the code I'm running in extendscript, identical to what is in the above JSFiddle (except $.println instead of console.log and an extra line showing that decrypting the obj works):
//JSON from Panel
jsonStr = '{"date":"1563662582633","email":"email#email.com","password":"1234324","uniqueID1":"12345","uniqueID2":"asfdsa-asdfsa-adsfas-sadfsdf-asfsaf\n"}';
//JSON from Panel
jsonStr = '{"date":"1563662582633","email":"email#email.com","password":"1234324","uniqueID1":"12345","uniqueID2":"asfdsa-asdfsa-adsfas-sadfsdf-asfsaf\n"}';
//Encrypt Data
var encrypted = CryptoJS.AES.encrypt(jsonStr, 'secret_passcode');
//Convert OBJ to String so I can save it
var encryptedString = encrypted.toString();
$.writeln('encryptedString is ' + encryptedString);
//Decrypt string - DOES NOT WORK IN EXTENDSCRIPT
var decryptedValue1= CryptoJS.AES.decrypt(encryptedString, 'secret_passcode');
$.writeln('decryptedValue1 is ' + decryptedValue1);
//Decrypt OBJ - WORKS IN EXTENDSCRIPT
var decryptedValue2= CryptoJS.AES.decrypt(encrypted, 'secret_passcode');
$.writeln('decryptedValue2 is ' + decryptedValue2);
//Final Decrypt output from string
$.writeln('finalOutput from decryptedValue1 is ' + decryptedValue1.toString(CryptoJS.enc.Utf8));
//Final Decrypt output from obj
$.writeln('finalOutput from decryptedValue2 is ' + decryptedValue2.toString(CryptoJS.enc.Utf8));
I'm guessing the issue is Extendscript using ES3. Any suggestions on how I can convert the encrypted data to a string (so I can store it as JSON) and then still be able to decrypt it? Obviously being able to store data I can't decrypt does me no good.
Thanks!
#include <ArduinoJson.h>
#include <SimpleDHT.h>
String input = "{\"temperature\":\"26\"};
SimpleDHT11 dht11;
byte temperature = 0;
int err = SimpleDHTErrSuccess;
void loop {
StaticJsonBuffer<512> dataBuffer;
if (err = dht11.read(2, &temperature, NULL)) == simpleDHTErrSuccess) {
Serial.print((int) temperature);
JsonObject& dataRoot = dataBuffer.parseObject(input);
*long Temperature = dataRoot[String("temperature")];
*Temperature = (long)temperature;
*dataRoot[String("temperature")] = Temperature;
String output;
dataRoot.printTo(output);
}
I have here a snippet of Arduino code used to format a DHT11 temperature sensor readings in JSON, to allow for live streaming of the data on a web client. This was obtained from this project I am using for inspiration https://www.twilio.com/blog/2018/07/watch-iot-sensors-esp32-javascript-nodejs-twilio-sync.html.
I am instead attempting to pull data from a Myoware muscle sensor. The amplitude value I am wanting can simply be queried like so:
int sensorValue = analogRead(A0);
I need help in understanding how the parseObject function works and what the purpose of the 'input' string is. All I want is for my sensor's value to be fed to the client side which displays it in a graph. The three lines I have asterisked are particularly confusing.
Thanks!
The method parseObject() allocates and populate a JsonObject (that you can work with) from a JSON string.
The "JsonObject" in your code example is named dataRoot and is defined with
JsonObject& dataRoot = dataBuffer.parseObject(input);
where dataBuffer comes from StaticJsonBuffer<512> dataBuffer; which is the entry point for using the ArduinoJson library, and
where input has the value of the JSON string "{\"temperature\":\"26\"}" which follows the standard JSON attribute-value pair format (you need a JSON string to work with and then send it to the client side).
After JsonObject& dataRoot = dataBuffer.parseObject(input); is executed, you get dataRoot as an object with a property named temperature and you can access this property with dataRoot[String("temperature")]
So the three lines:
long Temperature = dataRoot[String("temperature")];
Temperature = (long)temperature;
dataRoot[String("temperature")] = Temperature;
are used to update the value of the temperature attribute with whatever is read from the sensor.
A bit confusing in the example code is the fact that the name of the JSON attribute is temperature and also the name for the variable to hold the temperature read from sensor is also temperature. They are different things.
I am working on the requirement where a User can fetch the data from production box and insert it into developer sandbox by just giving production URL and creds. I am able to fetch data but somehow not able to convert the JSON to required object type. As I am newbie in Salesforce please don't mind for basic questions.
Below is the working logic and issue:
for(DataMigrationNAP__c d : dataMigrationNAP) // this loop will give all NAP object names and its corresponding fields like {'Account','Name,Phone,Id'},{'Opportunity', 'ID,Name, blah,blah'}...
{
final PageReference theUrl = new PageReference(SERVER_URL + '/services/data/v22.0/query/');
String soql = 'Select '+d.NAPObjectFields__c+' From '+d.Name+' a limit ' + recordCount;
theUrl.getParameters().put('q',soql);
request = new HttpRequest();
request.setEndpoint(theUrl.getUrl());
request.setMethod('GET');
request.setHeader('Authorization', 'OAuth ' + SESSION_ID);
String body = (new Http()).send(request).getBody();
JSONParser parser = JSON.createParser(body);
do{
parser.nextToken();
}while(parser.hasCurrentToken() && !'records'.equals(parser.getCurrentName()));
parser.nextToken();
String typeName = 'List<' + d.Name + '>';
Type t = Type.forName(typeName);
List<sobject> acc1 = (List<sobject>) parser.readValueAs(t);
insert acc1;
System.debug('Values inserted : ' + acc1);
}
Through above logic I am trying to fetch the data Object by Object and insert it into dev sandbox, I am able to fetch perfectly in JSON but not able to convert from JSON to required object. The issue is I can't hardcode Object or Type name because it will be a list of objects. Please let me know if you need any other detail and thanks in advance. Open for any other approach as well but it should be through apex coding only.
Have you tried JSON2Apex already, if not than this could be good candidate.
I'm trying to parse JSON data from URL and show the data in my app.
JSON Example (After accessing specific URL):
[{"placeID":"1","placeName":"Test Place","city":"New York","type":"Rest"..
How I can read this data and show a list of the places recieved from the API?
I've been trying ALL of the guides over the internet for parsing JSON data from URL with Android Studio and without. As a total beginner with Android developement, I couldn't make one working exmaple with json even when the author shared the final example for download. I hope you can help me in noob-friendly way and step by step or refer me to the right places.
Thank you!
I believe Android uses org.json as the JSON library, in which case something like this works to retrieve information about each place (assuming data is a valid JSON string)
try {
String data = "\"[{\"placeID\":\"1\",\"placeName\":\"Test Place\",\"city\":\"New York\",\"type\":\"Rest\"..";
JSONArray places = new JSONArray(data);
for (int i = 0; i < places.length(); i++)
JSONObject place = (JSONObject) places.get(i);
int id = place.getInt("id");
String name = place.getString("placeName");
String city = place.getString("city");
// etc...
// Do what you wish with the id, name, city and other variables.
// It loops through here for each item in the JSON variable.
}
} catch (JSONException e) {
e.printStackTrace();
}
This goes through each place in the JSON array and grabs some of the variables from it. It would probably be smart to create a data class and call it something like Place. You could then pass in the data with a constructor: new Place(id, name, city); (see this constructor for example: https://stackoverflow.com/a/22419370/5236779).
i need to parse a json file from the internet with my arduino uno r3
(i cannot change the output / file), i have to use it as it is...
My json file i get from the internet looks like this: (example from https://github.com/bblanchon/ArduinoJson)
char json[] = "{"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}";
The problem are the quotes "" inside the brackets,
If i change all quotes to \" everything works:
I provide an working Example from ArduinoJson library page:
char json[] = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
const char* sensor = root["sensor"];
long time = root["time"];
double latitude = root["data"][0];
double longitude = root["data"][1];
QUESTION:
How to replace the quotes, change them on the fly, or create the variable directly without the quotes, i need to parse the content afterwards.
Your problem is how you get the data from the client.
You only read one char and not all the data.
Try something like this:
I don't have a wifi or ethernet shield I cannot test, so I don't know if your lib will skip the http headers.
Try to print data after the loop to check.
char data[1024];
void loop(void ) {
int pos = 0;
memset(&data, 0, sizeof(data));
/* here your code for the GET
client.println("GET live.kvv.de/webapp/departures/bystop/…);
*/
while (client.available() && pos < sizeof(data) - 1) {
data[pos++] = client.read();
}
/* now you have all the data
XXX: check if you need to skip http headers
TODO: trigger an error is data is too small
*/
jsonBuffer.parseObject(data);