【发布时间】:2021-03-15 13:25:52
【问题描述】:
Photos:
- id: Photo1
Type: Color
Shade: Grey
- id: Photo2
Type: Color
Shade: Red
这里将上面的 yaml 文件转换为 JSON 对象并尝试根据 id 查找照片:
const raw = fs.readFileSync("Photos.yaml", 'utf8');
const PhotoData= YAML.load(raw);
export const getSpecificPhoto = (req,res)=>{
const { id } = req.params;
let photoArray = []; //photoArray
let getPhoto = JSON.stringify(PhotoData); //Converting to JSON string
photoArray.push(getPhoto); //Pushing to arrayv so that search can be done
console.log(photoArray);
const foundPhoto = photoArray.find((photo) => photo.id == id);
console.log(foundPhoto );
}
得到以下结果:
console.log(photoArray) => {"Photos":[{"id":"Photo1","Type":"Color","Shade":"Grey"},{"id":"Photo2","Type":"Color","Shade":"Red"}]}
console.log(foundPhoto) => undefined
问题:我怀疑获取“照片”:console.log(photoArray) 结果导致我基于 id 搜索照片失败。如何删除这个?我相信如果这被删除搜索和返回照片将起作用
【问题讨论】:
-
你在推
getLayout不应该是getPhoto吗?stringify也将对象转换为 json 字符串,而不是对象。你需要JSON.parse()那个字符串。 -
是的,在堆栈溢出时写在这里是一个错误。更正了
-
这里似乎断开了连接。
photoArray打印一个对象,但代码中没有任何地方将photoArray从一个数组重新分配给一个对象。 -
There's no such thing as a "JSON Object" 和
JSON.stringify(),顾名思义,返回一个字符串。 -
已更正@Andreas
标签: javascript node.js yaml