Serde_json doesn't parse this?

I've added a valetudo_state_watcher function to my src/main.rs · main · thomas351 / rust-influxdb-udp-logger · GitLab

I've expected this line to get parsed and reach the innermost if:

data: [{"__class":"AttachmentStateAttribute","metaData":{},"type":"watertank","attached":false},{"__class":"AttachmentStateAttribute","metaData":{},"type":"mop","attached":false},{"__class":"StatusStateAtt
ribute","metaData":{},"value":"idle","flag":"none"},{"__class":"BatteryStateAttribute","metaData":{},"level":83,"flag":"discharging"},{"__class":"PresetSelectionStateAttribute","metaData":{},"type":"fan_speed","value":"max"},{"__class":
"PresetSelectionStateAttribute","metaData":{},"type":"water_grade","value":"low"},{"__class":"ConsumableStateAttribute","metaData":{},"type":"brush","subType":"main","remaining":{"value":0,"unit":"minutes"}},{"__class":"ConsumableStateA
ttribute","metaData":{},"type":"brush","subType":"side_right","remaining":{"value":0,"unit":"minutes"}},{"__class":"ConsumableStateAttribute","metaData":{},"type":"filter","subType":"main","remaining":{"value":0,"unit":"minutes"}},{"__c
lass":"ConsumableStateAttribute","metaData":{},"type":"sensor","subType":"all","remaining":{"value":0,"unit":"minutes"}}]
if let Ok(value) = from_str::<Value>(&line) {
	if let Some(data) = value["data"].as_str() {
		println!("Received data: {}", data);
	}
	else {
		println!("couldn't extract data. value = {value}");
	}
}
else {
	println!("couldn't parse as json, line = {line}")
}

But the only line I've seen so far that doesn't end up in the last else block = "couldn't parse as json," was = "11".

Why? Is the problem, that the beginning reads data: instead of "data":? Can I make it more tolerant and accept strings without double-quotes? I don't control the software creating these events..

Yes it's because that key isn't quoted and doesn't seem to be in an object.

No you can't parse not-JSON with serde_json. You'll have to use a relaxed parser such as hjson or similar JSON variant.

2 Likes

If it's always "data: $VALID_JSON", you could just strip the "data:" part off.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.