0

I have 3 different types of properties like below

devices
iphone
ipad
ipod
watch

city
NY
SFO
LA
NJ

Company
Apple
Samsung
Walmart

Now I want create a json file using the properties.

For example for devices I have done like below.

I created a dictionary manually in python like below.

device_dict = {'device1': 'iphone', 'device2': 'ipad', 'device3': 'ipod', 'device4': 'watch'}

Then converted the dictionary to a json file like below.

import json
out_file = open("test.json","w")
json.dump(my_dict,out_file, indent=4)                                    
out_file.close()

I am able to create 3 separate json like below but How can I do for all the 3 properties into a single file.

4
  • The easiest solution is to create either a list of the three dicts, or a dict of the three dicts, and json.dump that. Commented May 10, 2018 at 21:27
  • For example: big_dict = {'device': device_dict, 'city': city_dict, 'company': company_dict} then json.dump(big_dict, out_file, indent=4). Commented May 10, 2018 at 21:28
  • (Although I'm not sure why your device_dict is a dict rather than a list in the first place…) Commented May 10, 2018 at 21:29
  • @abarnert I am still learning Python when i looked online I found articles to create json from dict mostly. I thought that is the easy way arround. Could you please let me know how I can create json file using lists Commented May 10, 2018 at 21:32

1 Answer 1

1

JSON allows list structures, so, without knowing what its for, the best way to save it in my opinion is as such:

data = {
    'devices': ['iphone', 'ipad', 'ipod', 'watch'],
    'cities': ['NY', 'SFO', 'LA', 'NJ'],
    'companies': ['Apple', 'Samsung', 'Walmart']
}

There is no point in naming something device1 when its obvious that it is the first item in the list of devices. When you want the value of the first device:

device1 = data['devices'][0]

This stores all the information in a format you can parse easily.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.