I'm fairly new to Arduino so I used a sample code before integrating this into my main code. I'm printing my value in a JSON format over serial. My Arduino outputs this and the python receives this and prints it in the same format
{
"value" : 5
}
but when I use python to try writing to a JSON file on my computer, I'm not getting the same JSON format. Can anyone figure out what's wrong? I need to write to my JSON file in JSON format, but instead, I'm getting this format written in my JSON file " \"value\": 5\r\n" instead of {"value: 5"}. Another problem I'm getting is that sometimes the values I get in my JSON get cut off so sometimes I end up with \r\n" or other parts of the current output. My goal is to get the python code to overwrite the JSON file in real-time, so whenever I open the JSON file, the entire output should be there in the correct JSON format. Any help is appreciated, thank you.
Arduino Code:
#include <ArduinoJson.h>
int analogPin = 3;
int data = 0;
char userInput;
StaticJsonDocument<100> testDocument;
char buffer[100];
void setup(){
Serial.begin(9600); // setup serial
StaticJsonDocument<100> testDocument;
testDocument["sensorType"] = "Temperature";
testDocument["value"] = 10;
char buffer[100];
serializeJsonPretty(testDocument, buffer);
Serial.println(buffer);
}
int(i)=1;
void loop(){
testDocument["value"] = i;
serializeJsonPretty(testDocument, buffer);
Serial.println(buffer);
i=i+1;
}
Python Code:
import serial
import json
import time
ser = serial.Serial('COM4', baudrate = 9600, timeout=1)
while 1:
data = (ser.readline().decode('ascii')) #split('\r\n')
#j = json.loads(data)
file = "C:/Users/Mike/Desktop/test.json"
my_data_file = open(file, 'w')
with open(file1, "w") as my_data_file :
json.dump(data, my_data_file)
print(data)
json.loads(data)line. Currently you are trying to json dump a string, which should be a data structure. if you want to dump the json, you first need to load it. Or you could completely ditch the python json and just write the received json string to the filej = json.loads(data)to get the data as python data structure (data must be a string with the complete json string). Then you can dump j to the file. You are getting the masking backslashes, because you are currently trying to dump a string instead of the data structure. And when saving a string in json, the json module must escape the special characters like"