【问题标题】:How to convert a string into array in Javascript [duplicate]如何在Javascript中将字符串转换为数组[重复]
【发布时间】:2020-09-12 09:46:12
【问题描述】:

如何转换“[{"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"}]

【问题讨论】:

  • 有什么区别?你试过什么?
  • 我正在尝试迭代第一个但出现错误,recipes.forEach 不是函数,因为它是字符串,当打印 typeof (firstArray)
  • 这是怎么回事?你如何得到这样的字符串..
  • 试图从 laravel Blade.php 访问这个,无法通过 api
  • 你不想要JSON.parse吗?

标签: javascript arrays json


【解决方案1】:

使用JSON.parse()

console.log(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"}]'))

【讨论】:

  • @ShubhamChaudhari :如果它对你有帮助,你可以接受它作为答案
【解决方案2】:

给定的字符串是 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 2015-11-11
    • 2019-07-29
    • 2011-12-06
    • 2016-09-20
    • 2020-08-22
    • 1970-01-01
    相关资源
    最近更新 更多