首页 > 解决方案 > 如何在Javascript中将字符串转换为数组

问题描述

如何转换“[{"id":6,"name":"r6","preparation_time":"123","servings":4,"background_media_file":"recipe_background_image","font_color":"#000000","created_at":"2020-09-11 09:27:02","updated_at":"2020-09-11 09:27:02"},{"id":5,"name":"r5","preparation_time":"21","servings":4,"background_media_file":"recipe_background_image","font_color":"#000000","created_at":"2020-09-11 09:26:28","updated_at":"2020-09-11 09:26:28"}]"

[{"id":6,"name":"r6","preparation_time":"123","servings":4,"background_media_file":"recipe_background_image","font_color":"#000000","created_at":"2020-09-11 09:27:02","updated_at":"2020-09-11 09:27:02"},{"id":5,"name":"r5","preparation_time":"21","servings":4,"background_media_file":"recipe_background_image","font_color":"#000000","created_at":"2020-09-11 09:26:28","updated_at":"2020-09-11 09:26:28"}]

标签: javascriptarraysjson

解决方案


给定的字符串是 json 格式。通过使用JSON.parse()

$arr = JSON.parse('[{"id":6,"name":"r6","preparation_time":"123","servings":4,"background_media_file":"recipe_background_image","font_color":"#000000","created_at":"2020-09-11 09:27:02","updated_at":"2020-09-11 09:27:02"},{"id":5,"name":"r5","preparation_time":"21","servings":4,"background_media_file":"recipe_background_image","font_color":"#000000","created_at":"2020-09-11 09:26:28","updated_at":"2020-09-11 09:26:28"}]');
console.log($arr);


推荐阅读