文章目录
c++ 读写
头文件
-
#include <nlohmann/json.hpp>
读
common_feature::StorageRelocatorMarks RelativeLocator::ReadFromFile(const std::string& path)
{
common_feature::StorageRelocatorMarks vLoad_storage_marks;
/// 检测 文件是否存在,不存在直接 return
std::ifstream file(path.c_str());
if (!file) {
LOG(ERROR)<<"could not open file:"+path;
return vLoad_storage_marks;
}
/// 读取 文件中所有数据
std::stringstream sst;
sst << file.rdbuf();
usleep(10000);
file.close();
/// 将数据 转化为 json 格式
std::string data = sst.str();
nlohmann::json doc = nlohmann::json::parse(data);
// check 肯定有 key:"version_no"
CHECK(doc.find("version_no") != doc.end());
LOG(ERROR)<<"find version_no: ";
// 取 key:"version_no" 的 value 值
std::string version_no = doc.at("version_no").get<std::string>();
LOG(ERROR)<<"version_no: "<<version_no;
// 检测 并 取 "mark_data"的 value, 该 value 也是 json 对象
CHECK(doc.find("mark_data") != doc.end());
doc = doc["mark_data"];
/// 遍历 "mark_data" json 对象
for(const auto& cd : doc.items()) {
std::string child_key = nlohmann::json(cd.key()).get<std::string>();
const nlohmann::json& child_doc = cd.value();
common_feature::StorageRelocatorMark vLoad_storage_mark;
CHECK(child_doc.find("mark_type") != child_doc.end());
vLoad_storage_mark.mark_type = child_doc.at("mark_type").get<uint8_t>();
CHECK(child_doc.find("assist_type") != child_doc.end());
vLoad_storage_mark.assist_type = child_doc.at("assist_type").get<uint8_t>();
CHECK(child_doc.find("id") != child_doc.end());
vLoad_storage_mark.id = child_doc["id"].get<int>();
double _x,_y,_z,_yaw,_roll,_pitch;
CHECK(child_doc.find("x") != child_doc.end());
_x = child_doc["x"].get<double>();
CHECK(child_doc.find("y") != child_doc.end());
_y = child_doc["y"].get<double>();
CHECK(child_doc.find("yaw") != child_doc.end());
_yaw = child_doc["yaw"].get<double>();
CHECK(child_doc.find("z") != child_doc.end());
_z = child_doc["z"].get<double>();
CHECK(child_doc.find("roll") != child_doc.end());
_roll = child_doc["roll"].get<double>();
CHECK(child_doc.find("pitch") != child_doc.end());
_pitch = child_doc["pitch"].get<double>();
vLoad_storage_mark.global_pose = Rigid3d(Eigen::Vector3d{_x,_y,_z},megbot_transform::RollPitchYaw(_roll,_pitch,_yaw));
vLoad_storage_marks.push_back(vLoad_storage_mark);
}
return vLoad_storage_marks;
}
写
注:
- -1、0 和 1 是 json.dumps() 函数中用于控制JSON格式化的 indent 参数的取值。
- indent=-1 生成最小化的缩进格式,indent=0 生成默认格式,indent=1 或更大的正整数生成带有指定空格数的缩进格式。
void RelativeLocator::SaveToFile(const std::string& path,const common_feature::StorageRelocatorMarks& vLoad_storage_marks)
{
LOG(ERROR)<<"start SaveToFile";
nlohmann::json doc;
doc["version_no"] = "relative_locator:0.0.1";
for(int i = 0; i< vLoad_storage_marks.size();i++) {
const common_feature::StorageRelocatorMark& vLoad_storage_mark = vLoad_storage_marks.at(i);
nlohmann::json child_doc;
child_doc["mark_type"] = uint8_t(vLoad_storage_mark.mark_type);
child_doc["assist_type"] = uint8_t(vLoad_storage_mark.assist_type);
child_doc["id"] = int(vLoad_storage_mark.id);
child_doc["x"] = (vLoad_storage_mark.global_pose.translation().x());
child_doc["y"] = (vLoad_storage_mark.global_pose.translation().y());
child_doc["z"] = (vLoad_storage_mark.global_pose.translation().z());
Eigen::Vector3d angle = RotationQuaternionToAngleAxisVector(vLoad_storage_mark.global_pose.rotation());
child_doc["roll"] = angle.x();
child_doc["pitch"] = angle.y();
child_doc["yaw"] = angle.z();
doc["mark_data"][std::to_string(i)] = child_doc;
}
std::string data = doc.dump(1);
std::ofstream file(path);
file<< data;
usleep(10000);
file.close();
}
proto to json
案例
-
///< proto 格式 megbot_locator_proto::RelocatorMark proto_relocator_mark; ///< proto 赋值 proto_relocator_mark.set_type(megbot_locator_proto::RelocatorMark_Type::RelocatorMark_Type_LASER_LINE_MARK); megbot_transform::Rigid3d target_in_mark,target_global_pose; *proto_relocator_mark.mutable_target_in_mark() = megbot_transform::ToProto(target_in_mark); *proto_relocator_mark.mutable_target_global_pose() = megbot_transform::ToProto(target_global_pose); // proto 数组赋值 std::vector<google::protobuf::uint64> sensor_ids = {16777216,16777217}; *proto_relocator_mark.mutable_sensor_ids() = {sensor_ids.begin(),sensor_ids.end()}; //前激光+后激光 megbot_sensor_proto::LaserVMark proto_mark; *proto_mark.mutable_pose() = megbot_transform::ToProto(target_global_pose*target_in_mark.inverse()); proto_mark.set_type(megbot_sensor_proto::LaserVMark_Type::LaserVMark_Type_PARALLEL_LINE); proto_mark.set_type_backup(int(common_feature::LaserFeatureType::PARALLEL_LINE)); // proto 类赋值 *proto_relocator_mark.mutable_laser_line_mark() = proto_mark; // Create a json_string from sr. std::string json_string; google::protobuf::util::JsonPrintOptions options; options.add_whitespace = true; options.always_print_primitive_fields = true; options.preserve_proto_field_names = true; google::protobuf::util::MessageToJsonString(proto_relocator_mark, &json_string, options); mark_msgs.emplace("laser_parallel_line_mark",json_string);
json-python
python 转换
- json.dumps 用于将 Python 对象编码成 JSON 字符串。
- json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型。
代码
-
#!/etc/bin/python #coding=utf-8 import json list_obj = [[1,2,3],123,123.123,'abc',{'key1':(1,2,3),'key2':(4,5,6)}] encoded_json = json.dumps(list_obj,indent=4) data_json = json.loads(encoded_json) print(type(list_obj)) print(list_obj) print(type(encoded_json)) print(encoded_json) print(type(data_json)) print(data_json)
输出:
-
<type 'list'> [[1, 2, 3], 123, 123.123, 'abc', {'key2': (4, 5, 6), 'key1': (1, 2, 3)}] <type 'str'> [ [ 1, 2, 3 ], 123, 123.123, "abc", { "key2": [ 4, 5, 6 ], "key1": [ 1, 2, 3 ] } ] <type 'list'> [[1, 2, 3], 123, 123.123, u'abc', {u'key2': [4, 5, 6], u'key1': [1, 2, 3]}]
保存加载文件
- dump() 将python对象写入文件
- load()从文件中读取json数据
代码
-
#!/etc/bin/python #coding=utf-8 import json ### test_dict.json test_dict = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75, "target_in_mark": { "translation": { "x": -0.4, "y": 0, "z": 0 }, "rotation": { "x": 0, "y": 0, "z": 0, "w": 1 } }, "sensor_ids": [ 11111111, 22222222, 33333333 ] } print("test_dict value!") with open('test_dict.json', 'w') as f: json.dump(test_dict,f,indent = 4) print("save test_dict to test_dict.json") a = None with open('test_dict.json', 'r') as f: a = json.load(f) print(type(a)) print(a) print("read test_dict.json and print in screen") a["test"] = {"sub_test": [ 1,2,3]} print("add sub_test msgs") with open('a.json', 'w') as f: json.dump(a,f,indent = 4) print("save to a.json")
遍历
在Python中,你可以通过多种方式来查看JSON对象(通常被转换为Python的字典类型)中的keys。这里有一些常用的方法:
使用keys()
方法
当你将JSON字符串转换为Python的字典类型后,可以使用字典的keys()
方法来获取所有keys的视图对象(dict_keys
),然后你可以遍历这个对象或者将其转换为列表进行查看。
import json
json_str = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_str) # 将JSON字符串转换为Python字典
# 查看所有keys
print(data.keys()) # 输出:dict_keys(['name', 'age', 'city'])
# 将keys转换为列表
print(list(data.keys())) # 输出:['name', 'age', 'city']
直接遍历
你也可以直接遍历字典来查看每个key。
for key in data:
print(key)
# 输出:
# name
# age
# city
使用items()
或values()
虽然items()
和values()
方法主要用于获取字典的项(键值对)或值,但了解它们的存在对于全面理解字典操作也是有帮助的。
items()
:返回字典的(键,值)对列表。values()
:返回字典中所有的值。
# 使用items()查看key和value
for key, value in data.items():
print(f"Key: {key}, Value: {value}")
# 使用values()仅查看values(虽然不直接查看key,但这里提及完整性)
for value in data.values():
print(value)
是否存在
if 'name' in data:
进行判断
import json
# 假设我们有一个JSON字符串
json_str = '{"name": "John", "age": 30, "city": "New York"}'
# 将JSON字符串解析为Python字典
data = json.loads(json_str)
# 判断'name'这个key是否存在
if 'name' in data:
print("Key 'name' exists.")
print(f"The value of 'name' is: {data['name']}")
else:
print("Key 'name' does not exist.")
# 判断'email'这个key是否存在
if 'email' in data:
print("Key 'email' exists.")
else:
print("Key 'email' does not exist.")