-1

I have json output and I would like to convert it into below format. I'm using ast.literaleval, I would like to have desired sorted by id and name in single quotes. I used ordered dict for desired order but not sure how to convert double quotes to single quotes for desired output. Any help appreciated. I'm using Python.

json_result=[{"name":"sample name","id":77}]

desired_output=[{'id':77,'name':'sample name'}]
Kay
  • 7
  • 1
  • 7
  • 2
    You should explain *why* you want this. This is invalid JSON, and dicts are unordered. – Daniel Roseman Mar 10 '18 at 22:42
  • Thanks for your comment. I'm sorry was not able explain my question correctly. What I would like to do is change the order the keys? How to achieve it? I converted it into order dict but when I converted it back to dict. It is going back to old format. – Kay Mar 10 '18 at 22:53
  • Of course when you convert back to a regular dict it loses the order, **dict objects are inherently unordered**. If you want to maintain order, use an ordered data-structure. Converting to an ordered data-structure and back to an unordered one won't magically make the unordered one ordered. This looks like a good use-case for a `collections.namedtuple`, for example – juanpa.arrivillaga Mar 10 '18 at 22:57
  • Why are you using `ast.literal_eval`? If that *is* JSON then wouldn't, err, `json` be a better bet? `'True' != 'true'`, for example. – jonrsharpe Mar 10 '18 at 23:04

1 Answers1

1

What do you mean convert double to single quotes? That is generally only applicable within a string which contains single/double quotes.

In this case json_result is a list of size 1 of a dict with keys and values which don't contain any double or single quotes within the strings. Therefore the object has no knowledge of whether you define the strings with single or double quotes.

They are interchangable in defining a string

For example: x = "hello" is equivalent to x = 'hello'

If you simply try:

json_result=[{"name":"sample name","id":77}]

print(json_result)

You get

[{'name': 'sample name', 'id': 77}]
NickHilton
  • 662
  • 6
  • 13
  • Thanks. This made sense. I was confused initially. How can I get the order change. I would like to have id and then name. – Kay Mar 10 '18 at 22:50
  • @Kay why do you think the order matters? You get values from a dictionary by *key*, not by index. – jonrsharpe Mar 10 '18 at 23:02