Convert JSON array to Python list

后端 未结 3 632
孤城傲影
孤城傲影 2020-12-07 15:30
import json

array = \'{\"fruits\": [\"apple\", \"banana\", \"orange\"]}\'
data  = json.loads(array)

That is my JSON array, but I would want to con

相关标签:
3条回答
  • 2020-12-07 15:56
    import json
    
    array = '{"fruits": ["apple", "banana", "orange"]}'
    data  = json.loads(array)
    print data['fruits']
    # the print displays:
    # [u'apple', u'banana', u'orange']
    

    You had everything you needed. data will be a dict, and data['fruits'] will be a list

    0 讨论(0)
  • 2020-12-07 15:58

    Tested on Ideone.

    
    import json
    array = '{"fruits": ["apple", "banana", "orange"]}'
    data  = json.loads(array)
    fruits_list = data['fruits']
    print fruits_list
    
    0 讨论(0)
  • 2020-12-07 16:15

    data will return you a string representation of a list, but it is actually still a string. Just check the type of data with type(data). That means if you try using indexing on this string representation of a list as such data['fruits'][0], it will return you "[" as it is the first character of data['fruits']

    You can do json.loads(data['fruits']) to convert it back to a Python list so that you can interact with regular list indexing. There are 2 other ways you can convert it back to a Python list suggested here

    0 讨论(0)
提交回复
热议问题