简体   繁体   中英

Converting to json re-orders objects in python

I'm trying to get a response from http://steamcommunity.com/profiles/76561198081591043/inventory/json/730/2 in python using requests.

import requests    
url =  "http://steamcommunity.com/profiles/76561198081591043/inventory/json/730/2"   
r = requests.get(url)
print r.text
print r.json()

r.text and r.json() return the objects ordered differently. In 'rgInventory' for instance the first 3 "ids": in .text end in 925, 658, 891 but in .json() end in 891, 619, 741 (just co-incidence that they're descending).

json.loads(r.text) yields the same result

How do i get the json objects to be in the same order as .text shows them?

This is probably unnecessary, and if it is necessary, either your code or the Steam API is broken. Judging by your comments, it's probably unnecessary. That said, it's doable.

json.loads takes an optional object_pairs_hook argument. This specifies a function that will be called with a list of key-value pairs to decode object literals. The default is equivalent to specifying object_pairs_hook=dict ; to preserve the order the keys appeared in the raw text, you can use object_pairs_hook=collections.OrderedDict :

import collections, json
data = json.loads(response_string, object_pairs_hook=collections.OrderedDict)

r.json() passes keyword arguments along to json.loads , so it should support the same argument:

data = r.json(object_pairs_hook=collections.OrderedDict)

JSON objects are not sorted per definition of javascript ( Does JavaScript Guarantee Object Property Order? ). To get the desired result, you would have to sort the resulting dictionary by keys: How can I sort a dictionary by key?

The order of fields in a JSON object is explicitly meaningless and need not be preserved. Many implementations are hashtables, for efficiency.

If JSON order matters, you MUST use an array -- in this case the simplest model might be an array containing two-element arrays, each of which in turn contains a string name and a value.

The other solution would be to use non-JSON string processing code to massage the JSON object fields back into your preferred order. Not recommended!

Sorry, but a difference which the spec doesn't recognize is simply not a difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM