0

I am beginner to working with JSON, and now i'm gonna play it with Python. Recently i have make code like this:

import json


def product():
    itemId = 84576454
    itemName = 'FGX Flannel Shirt'
    price = 195000
    availableColorAndSize = {
        'color': {'blue-black': ['M', 'L', 'XL'],
                  'black-white': ['L']}
    }

    freeShiping = False

The output file should look something like this:

{"Stuff":{
    "id":84576454,
    "name":"Shoes",
    "cost":431200,
    "color_and_size": {
        "color": {
            "brown":["XL", "XXL", "M"],
            "green":["XXL"]
        }
    }
}
}

Before i have follow this one: Store Python function in JSON But i'm still confused and not sure how to return that function to make a JSON.

5
  • 1
    What exactly do you mean "return a JSON file"? Have you done some research around the functionality Python has for dealing with JSON?
    – jonrsharpe
    Nov 17, 2018 at 13:31
  • @jonrsharpe return a value in JSON format
    – Tri
    Nov 17, 2018 at 13:33
  • So do you mean as a string?
    – jonrsharpe
    Nov 17, 2018 at 13:33
  • @jonrsharpe yeah, right.. sorry but i have try research this code before stackoverflow.com/questions/51936785/…
    – Tri
    Nov 17, 2018 at 13:35
  • 1
    Spend some time skimming the standard library. You never know what you might find.
    – chepner
    Nov 17, 2018 at 13:35

1 Answer 1

4

Python's built-in JSON library can do this for you. The four main functions are as follows:

json.load() loads a JSON formatted file and returns a Python dictionary >object.

json.loads() returns a Python dictionary object from a JSON formatted string.

json.dump() returns a JSON formatted file from a Python dictionary object

json.dumps() returns a JSON formatted string from a Python dictionary object

So you could use:

import json


def product():
    itemId = 12341822
    itemName = 'FGX Flannel Shirt'
    price = 195000
    availableColorAndSize = {
        'color': {'blue-black': ['M', 'L', 'XL'],
                  'black-white': ['L']}
    }

    freeShiping = False
    
    # Returns a JSON formatted file based on the dictionary shown
    return json.dump(
        {'itemId': itemId,
         'itemName': itemName,
         'price': price,
         'availableColorAndSize': availableColorAndSize,
         'freeShiping': freeShiping})
1
  • 1
    Thank you so much @wiomoc, its work perfectly.
    – Tri
    Nov 17, 2018 at 14:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.