How to convert data into JSON dictionary?












0














So I get a response and print it. The result is bytes:



payload = request.body
print (payload)
b'a=123&b=345&c=678&d=910'


I decode it, and the result is:



dataform = payload.decode('utf-8').replace("'", '"')
print(dataform, 'dataform')
a=123&b=345&c=678&d=910


I dumps it, and the result is:



result = json.dumps(dataform, indent=4, sort_keys=True)
print(result, 'result')
"a=123&b=345&c=678&d=910"


I loads it, and the result is:



jason = json.loads(result)
print(jason, 'jason')
a=123&b=345&c=678&d=910


I just want a normal json dictionary that I can refer to like data['string']. What am I doing wrong or not doing?










share|improve this question




















  • 1




    The string doesn't contain any single quotes, so replacing them is superfluous (and if it wasn't, it'd be wrong). Other than that, are you looking for d = dict(x.split('=', 1) for x in payload.decode('utf-8').split('&')) perhaps?
    – tripleee
    Nov 23 '18 at 9:18
















0














So I get a response and print it. The result is bytes:



payload = request.body
print (payload)
b'a=123&b=345&c=678&d=910'


I decode it, and the result is:



dataform = payload.decode('utf-8').replace("'", '"')
print(dataform, 'dataform')
a=123&b=345&c=678&d=910


I dumps it, and the result is:



result = json.dumps(dataform, indent=4, sort_keys=True)
print(result, 'result')
"a=123&b=345&c=678&d=910"


I loads it, and the result is:



jason = json.loads(result)
print(jason, 'jason')
a=123&b=345&c=678&d=910


I just want a normal json dictionary that I can refer to like data['string']. What am I doing wrong or not doing?










share|improve this question




















  • 1




    The string doesn't contain any single quotes, so replacing them is superfluous (and if it wasn't, it'd be wrong). Other than that, are you looking for d = dict(x.split('=', 1) for x in payload.decode('utf-8').split('&')) perhaps?
    – tripleee
    Nov 23 '18 at 9:18














0












0








0







So I get a response and print it. The result is bytes:



payload = request.body
print (payload)
b'a=123&b=345&c=678&d=910'


I decode it, and the result is:



dataform = payload.decode('utf-8').replace("'", '"')
print(dataform, 'dataform')
a=123&b=345&c=678&d=910


I dumps it, and the result is:



result = json.dumps(dataform, indent=4, sort_keys=True)
print(result, 'result')
"a=123&b=345&c=678&d=910"


I loads it, and the result is:



jason = json.loads(result)
print(jason, 'jason')
a=123&b=345&c=678&d=910


I just want a normal json dictionary that I can refer to like data['string']. What am I doing wrong or not doing?










share|improve this question















So I get a response and print it. The result is bytes:



payload = request.body
print (payload)
b'a=123&b=345&c=678&d=910'


I decode it, and the result is:



dataform = payload.decode('utf-8').replace("'", '"')
print(dataform, 'dataform')
a=123&b=345&c=678&d=910


I dumps it, and the result is:



result = json.dumps(dataform, indent=4, sort_keys=True)
print(result, 'result')
"a=123&b=345&c=678&d=910"


I loads it, and the result is:



jason = json.loads(result)
print(jason, 'jason')
a=123&b=345&c=678&d=910


I just want a normal json dictionary that I can refer to like data['string']. What am I doing wrong or not doing?







python json






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 9:10







Whodini

















asked Nov 23 '18 at 9:03









WhodiniWhodini

50913




50913








  • 1




    The string doesn't contain any single quotes, so replacing them is superfluous (and if it wasn't, it'd be wrong). Other than that, are you looking for d = dict(x.split('=', 1) for x in payload.decode('utf-8').split('&')) perhaps?
    – tripleee
    Nov 23 '18 at 9:18














  • 1




    The string doesn't contain any single quotes, so replacing them is superfluous (and if it wasn't, it'd be wrong). Other than that, are you looking for d = dict(x.split('=', 1) for x in payload.decode('utf-8').split('&')) perhaps?
    – tripleee
    Nov 23 '18 at 9:18








1




1




The string doesn't contain any single quotes, so replacing them is superfluous (and if it wasn't, it'd be wrong). Other than that, are you looking for d = dict(x.split('=', 1) for x in payload.decode('utf-8').split('&')) perhaps?
– tripleee
Nov 23 '18 at 9:18




The string doesn't contain any single quotes, so replacing them is superfluous (and if it wasn't, it'd be wrong). Other than that, are you looking for d = dict(x.split('=', 1) for x in payload.decode('utf-8').split('&')) perhaps?
– tripleee
Nov 23 '18 at 9:18












3 Answers
3






active

oldest

votes


















2














There's a few errors here.



First off, dumping to JSON and then loading it again does absolutely nothing (it does have a few side-effects, but that's not important here).



Secondly, and mainly, your input data isn't JSON - it's either a query string or, more likely, form-data.



You can try to parse it using the standard parse_qs in urllib.parse, but if that fails you'll have to look around for a library that can handle proper form data.



In [1]: from urllib.parse import parse_qs

In [2]: payload = b'a=123&b=345&c=678&d=910'

In [3]: dataform = payload.decode('utf-8').replace("'", '"')

In [4]: result = parse_qs(dataform)

In [5]: print(result)
{'a': ['123'], 'b': ['345'], 'c': ['678'], 'd': ['910']}





share|improve this answer

















  • 1




    The .replace() part is superfluous. Also in python2, you should do from urlparse import parse_qs.
    – SMir
    Nov 23 '18 at 9:23












  • the parse_qs is what I needed. Thanks. I did not know of that.
    – Whodini
    Nov 23 '18 at 9:32



















1














At first, you need to convert the string (here, as the example, to the array, but you can use that you want)



data = [x.split('=') for x in data.split('&')]
>>> data
[['a', '123'], ['b', '345'], ['c', '678'], ['d', '910']]


And after this, you can easily create the dictionary.



dict = {key: value for (key,value) in data}
>>> dict
{'a': '123', 'c': '678', 'b': '345', 'd': '910'}


Or if you want to store numbers as int:



dict = {key: int(value) for (key,value) in data}
>>> dict
{'a': 123, 'c': 678, 'b': 345, 'd': 910}





share|improve this answer































    1














    import json
    from urllib.parse import parse_qs

    payload = request.body
    # b'a=123&b=345&c=678&d=910'

    qs = parse_qs(payload.decode())
    # {'a': ['123'], 'b': ['345'], 'c': ['678'], 'd': ['910']}


    Convert list values and convert data into JSON



    json.dumps({k: v[0] for k, v in qs.items()})
    # '{"a": "123", "b": "345", "c": "678", "d": "910"}'





    share|improve this answer



















    • 2




      An explanation, what the posted code does and how this addresses the problem in the question, rarely fails to improve an answer.
      – blue-phoenox
      Nov 23 '18 at 9:35











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53443490%2fhow-to-convert-data-into-json-dictionary%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    There's a few errors here.



    First off, dumping to JSON and then loading it again does absolutely nothing (it does have a few side-effects, but that's not important here).



    Secondly, and mainly, your input data isn't JSON - it's either a query string or, more likely, form-data.



    You can try to parse it using the standard parse_qs in urllib.parse, but if that fails you'll have to look around for a library that can handle proper form data.



    In [1]: from urllib.parse import parse_qs

    In [2]: payload = b'a=123&b=345&c=678&d=910'

    In [3]: dataform = payload.decode('utf-8').replace("'", '"')

    In [4]: result = parse_qs(dataform)

    In [5]: print(result)
    {'a': ['123'], 'b': ['345'], 'c': ['678'], 'd': ['910']}





    share|improve this answer

















    • 1




      The .replace() part is superfluous. Also in python2, you should do from urlparse import parse_qs.
      – SMir
      Nov 23 '18 at 9:23












    • the parse_qs is what I needed. Thanks. I did not know of that.
      – Whodini
      Nov 23 '18 at 9:32
















    2














    There's a few errors here.



    First off, dumping to JSON and then loading it again does absolutely nothing (it does have a few side-effects, but that's not important here).



    Secondly, and mainly, your input data isn't JSON - it's either a query string or, more likely, form-data.



    You can try to parse it using the standard parse_qs in urllib.parse, but if that fails you'll have to look around for a library that can handle proper form data.



    In [1]: from urllib.parse import parse_qs

    In [2]: payload = b'a=123&b=345&c=678&d=910'

    In [3]: dataform = payload.decode('utf-8').replace("'", '"')

    In [4]: result = parse_qs(dataform)

    In [5]: print(result)
    {'a': ['123'], 'b': ['345'], 'c': ['678'], 'd': ['910']}





    share|improve this answer

















    • 1




      The .replace() part is superfluous. Also in python2, you should do from urlparse import parse_qs.
      – SMir
      Nov 23 '18 at 9:23












    • the parse_qs is what I needed. Thanks. I did not know of that.
      – Whodini
      Nov 23 '18 at 9:32














    2












    2








    2






    There's a few errors here.



    First off, dumping to JSON and then loading it again does absolutely nothing (it does have a few side-effects, but that's not important here).



    Secondly, and mainly, your input data isn't JSON - it's either a query string or, more likely, form-data.



    You can try to parse it using the standard parse_qs in urllib.parse, but if that fails you'll have to look around for a library that can handle proper form data.



    In [1]: from urllib.parse import parse_qs

    In [2]: payload = b'a=123&b=345&c=678&d=910'

    In [3]: dataform = payload.decode('utf-8').replace("'", '"')

    In [4]: result = parse_qs(dataform)

    In [5]: print(result)
    {'a': ['123'], 'b': ['345'], 'c': ['678'], 'd': ['910']}





    share|improve this answer












    There's a few errors here.



    First off, dumping to JSON and then loading it again does absolutely nothing (it does have a few side-effects, but that's not important here).



    Secondly, and mainly, your input data isn't JSON - it's either a query string or, more likely, form-data.



    You can try to parse it using the standard parse_qs in urllib.parse, but if that fails you'll have to look around for a library that can handle proper form data.



    In [1]: from urllib.parse import parse_qs

    In [2]: payload = b'a=123&b=345&c=678&d=910'

    In [3]: dataform = payload.decode('utf-8').replace("'", '"')

    In [4]: result = parse_qs(dataform)

    In [5]: print(result)
    {'a': ['123'], 'b': ['345'], 'c': ['678'], 'd': ['910']}






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 23 '18 at 9:19









    RanizRaniz

    8,27312155




    8,27312155








    • 1




      The .replace() part is superfluous. Also in python2, you should do from urlparse import parse_qs.
      – SMir
      Nov 23 '18 at 9:23












    • the parse_qs is what I needed. Thanks. I did not know of that.
      – Whodini
      Nov 23 '18 at 9:32














    • 1




      The .replace() part is superfluous. Also in python2, you should do from urlparse import parse_qs.
      – SMir
      Nov 23 '18 at 9:23












    • the parse_qs is what I needed. Thanks. I did not know of that.
      – Whodini
      Nov 23 '18 at 9:32








    1




    1




    The .replace() part is superfluous. Also in python2, you should do from urlparse import parse_qs.
    – SMir
    Nov 23 '18 at 9:23






    The .replace() part is superfluous. Also in python2, you should do from urlparse import parse_qs.
    – SMir
    Nov 23 '18 at 9:23














    the parse_qs is what I needed. Thanks. I did not know of that.
    – Whodini
    Nov 23 '18 at 9:32




    the parse_qs is what I needed. Thanks. I did not know of that.
    – Whodini
    Nov 23 '18 at 9:32













    1














    At first, you need to convert the string (here, as the example, to the array, but you can use that you want)



    data = [x.split('=') for x in data.split('&')]
    >>> data
    [['a', '123'], ['b', '345'], ['c', '678'], ['d', '910']]


    And after this, you can easily create the dictionary.



    dict = {key: value for (key,value) in data}
    >>> dict
    {'a': '123', 'c': '678', 'b': '345', 'd': '910'}


    Or if you want to store numbers as int:



    dict = {key: int(value) for (key,value) in data}
    >>> dict
    {'a': 123, 'c': 678, 'b': 345, 'd': 910}





    share|improve this answer




























      1














      At first, you need to convert the string (here, as the example, to the array, but you can use that you want)



      data = [x.split('=') for x in data.split('&')]
      >>> data
      [['a', '123'], ['b', '345'], ['c', '678'], ['d', '910']]


      And after this, you can easily create the dictionary.



      dict = {key: value for (key,value) in data}
      >>> dict
      {'a': '123', 'c': '678', 'b': '345', 'd': '910'}


      Or if you want to store numbers as int:



      dict = {key: int(value) for (key,value) in data}
      >>> dict
      {'a': 123, 'c': 678, 'b': 345, 'd': 910}





      share|improve this answer


























        1












        1








        1






        At first, you need to convert the string (here, as the example, to the array, but you can use that you want)



        data = [x.split('=') for x in data.split('&')]
        >>> data
        [['a', '123'], ['b', '345'], ['c', '678'], ['d', '910']]


        And after this, you can easily create the dictionary.



        dict = {key: value for (key,value) in data}
        >>> dict
        {'a': '123', 'c': '678', 'b': '345', 'd': '910'}


        Or if you want to store numbers as int:



        dict = {key: int(value) for (key,value) in data}
        >>> dict
        {'a': 123, 'c': 678, 'b': 345, 'd': 910}





        share|improve this answer














        At first, you need to convert the string (here, as the example, to the array, but you can use that you want)



        data = [x.split('=') for x in data.split('&')]
        >>> data
        [['a', '123'], ['b', '345'], ['c', '678'], ['d', '910']]


        And after this, you can easily create the dictionary.



        dict = {key: value for (key,value) in data}
        >>> dict
        {'a': '123', 'c': '678', 'b': '345', 'd': '910'}


        Or if you want to store numbers as int:



        dict = {key: int(value) for (key,value) in data}
        >>> dict
        {'a': 123, 'c': 678, 'b': 345, 'd': 910}






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 23 '18 at 9:19









        tripleee

        89.1k12124181




        89.1k12124181










        answered Nov 23 '18 at 9:18









        Ihor VoroninIhor Voronin

        1856




        1856























            1














            import json
            from urllib.parse import parse_qs

            payload = request.body
            # b'a=123&b=345&c=678&d=910'

            qs = parse_qs(payload.decode())
            # {'a': ['123'], 'b': ['345'], 'c': ['678'], 'd': ['910']}


            Convert list values and convert data into JSON



            json.dumps({k: v[0] for k, v in qs.items()})
            # '{"a": "123", "b": "345", "c": "678", "d": "910"}'





            share|improve this answer



















            • 2




              An explanation, what the posted code does and how this addresses the problem in the question, rarely fails to improve an answer.
              – blue-phoenox
              Nov 23 '18 at 9:35
















            1














            import json
            from urllib.parse import parse_qs

            payload = request.body
            # b'a=123&b=345&c=678&d=910'

            qs = parse_qs(payload.decode())
            # {'a': ['123'], 'b': ['345'], 'c': ['678'], 'd': ['910']}


            Convert list values and convert data into JSON



            json.dumps({k: v[0] for k, v in qs.items()})
            # '{"a": "123", "b": "345", "c": "678", "d": "910"}'





            share|improve this answer



















            • 2




              An explanation, what the posted code does and how this addresses the problem in the question, rarely fails to improve an answer.
              – blue-phoenox
              Nov 23 '18 at 9:35














            1












            1








            1






            import json
            from urllib.parse import parse_qs

            payload = request.body
            # b'a=123&b=345&c=678&d=910'

            qs = parse_qs(payload.decode())
            # {'a': ['123'], 'b': ['345'], 'c': ['678'], 'd': ['910']}


            Convert list values and convert data into JSON



            json.dumps({k: v[0] for k, v in qs.items()})
            # '{"a": "123", "b": "345", "c": "678", "d": "910"}'





            share|improve this answer














            import json
            from urllib.parse import parse_qs

            payload = request.body
            # b'a=123&b=345&c=678&d=910'

            qs = parse_qs(payload.decode())
            # {'a': ['123'], 'b': ['345'], 'c': ['678'], 'd': ['910']}


            Convert list values and convert data into JSON



            json.dumps({k: v[0] for k, v in qs.items()})
            # '{"a": "123", "b": "345", "c": "678", "d": "910"}'






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 23 '18 at 10:42

























            answered Nov 23 '18 at 9:13









            vczmvczm

            413




            413








            • 2




              An explanation, what the posted code does and how this addresses the problem in the question, rarely fails to improve an answer.
              – blue-phoenox
              Nov 23 '18 at 9:35














            • 2




              An explanation, what the posted code does and how this addresses the problem in the question, rarely fails to improve an answer.
              – blue-phoenox
              Nov 23 '18 at 9:35








            2




            2




            An explanation, what the posted code does and how this addresses the problem in the question, rarely fails to improve an answer.
            – blue-phoenox
            Nov 23 '18 at 9:35




            An explanation, what the posted code does and how this addresses the problem in the question, rarely fails to improve an answer.
            – blue-phoenox
            Nov 23 '18 at 9:35


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53443490%2fhow-to-convert-data-into-json-dictionary%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Berounka

            Sphinx de Gizeh

            Different font size/position of beamer's navigation symbols template's content depending on regular/plain...