0
votes

I am new to python. I want to extract the elements of array 'Address' from below json. I am trying to use map to split the elements using

r=<below json>
s=r["Customer"]
y=s.map(lambda x:x.split(",")) 

But I am getting the error as .....AttributeError: 'str' object has no attribute 'map'

Can you please advise which is the best way to do this.

{ "id": "981",
  "Customer": 
[
  {
    "Name": "abc",
    "Title": "Mr",
    "Gender": "M",
    "Address": [
      {
    "Postcode": "2GF",
    "StreetName": "Black Street",
    "FlatNo": "123",
      }
    ]
  },
  {
    "Name": "xyz",
    "Title": "Mrs",
    "Gender": "F",
    "Address": [
      {
    "Postcode": "2CX",
    "StreetName": "White Street",
    "FlatNo": "123",
      }
    ]
  }
]
}
2
This doesn't answer your question, but consider using the built-in json module to parse json instead of splitting values out of it manually.Kevin
What is r when you are using r.map()?Brendan Martin
First and foremost: Welcome to Stack Overflow! Now: As Kevin already pointed out, you should probably parse the string with the json module first.CodenameLambda
I'm not aware of a single python data structure that has a .map method. Where'd you get that from?Aran-Fey
I'm confused. Is r a string or a dict? If it's a string, then s=r["Customer"] should crash with TypeError: string indices must be integers. If it's a dict and if the value associated with "Customer" is a list, then s.map should crash with AttributeError: 'list' object has no attribute 'map'. In either case, you should not be getting AttributeError: 'str' object has no attribute 'map'. Can you provide a minimal reproducible example?Kevin

2 Answers

0
votes

"I want to extract the elements of array 'Address' from below json":

[x for dd in r['Customer'] for x in dd['Address']]
0
votes

Why not just:

data = { id: 981,
  'Customer':
[
  {
    "Name": "abc",
    "Title": "Mr",
    "Gender": "M",
    "Address": [
      {
    "Postcode": "2GF",
    "StreetName": "Black Street",
    "FlatNo": "123",
      }
    ]
  },
  {
    "Name": "xyz",
    "Title": "Mrs",
    "Gender": "F",
    "Address": [
      {
    "Postcode": "2CX",
    "StreetName": "White Street",
    "FlatNo": "123",
      }
    ]
  }
]
}


for item in data['Customer']:
    for data_item in item['Address']:
        print(data_item['Postcode'], data_item['StreetName'], data_item['FlatNo'])

OUTPUT:

2GF Black Street 123
2CX White Street 123