【问题标题】:Convert Json object to array in nodejs在nodejs中将Json对象转换为数组
【发布时间】: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


【解决方案1】:

您的数据位于Photos 对象中,然后您推入一个空数组。 所以从数组中查找时,需要从正确的位置获取。

正确代码:

(function test(id) {
let PhotoData = "{\"Photos\":[{\"id\":\"Photo1\", \"Type\": \"Color\", \"Shade\": \"Grey\"}, {\"id\": \"Photo2\", \"Type\": \"Color\", \"Shade\": \"Red\"}]}"
let photoArray = []; //photoArray
let getPhoto = JSON.parse(PhotoData);  //Converting to JSON object
console.log(getPhoto);
photoArray.push(getPhoto); //Pushing to arrayv so that search can be done
console.log(photoArray);
const foundPhoto = photoArray[0].Photos.find((photo) => photo.id == id);

console.log(foundPhoto );
})("Photo1");

结果:

{id: "Photo1", Type: "Color", Shade: "Grey"}

【讨论】:

    【解决方案2】:

    奇怪的是,您将这个带有照片的对象转换回带有JSON.stringify() 的字符串,然后将该字符串添加到数组中。请参阅下面的建议。

    const existingArrayOfPhotos = [];
    
    yamlString = `Photos:
          - id: Photo1
            Type: Color
            Shade: Grey
          - id: Photo2
            Type: Color
            Shade: Red`
            
    const photoData = YAML.parse(yamlString);
    existingArrayOfPhotos.push(...photoData.Photos)
    const foundPhoto = existingArrayOfPhotos.find((photo) => photo.id == "Photo1");
    
    console.log(foundPhoto);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/yamljs/0.3.0/yaml.min.js"></script>

    【讨论】:

      猜你喜欢
      • 2016-08-03
      • 2017-08-17
      • 2017-03-29
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 2012-07-21
      相关资源
      最近更新 更多