1

I am trying to parse the following JSON using Python / Django:

[
  {
    "street": "KEELER",
    ":id": 1421
  }
]

Within my Django templates, I can successfully access the street key like:

{{ obj.street }}

but cannot access the id. I have tried the following (all taken from various SO questions):

{{ obj.id }} , {{ obj.:id }}, {{ obj[':id'] }}

I have seen the couple of other questions in SO addressing a similar issue, but none seem to help.

Endophage
  • 21,038
  • 13
  • 59
  • 90
Progger
  • 2,266
  • 4
  • 27
  • 51
  • 1
    Try to fix the json data rather than trying to figuring out how to work with bad json data. – Aamir Rind Jun 17 '13 at 15:49
  • this is json data coming from a government site using Socrata Open Data api (soda). I have no access to it. This is how the data is presented. – Progger Jun 17 '13 at 15:51
  • 2
    Is the close quote on :id intentionally missing? – Pace Jun 17 '13 at 15:52
  • What json parser (what does your import and parse code look like) and python version are you using? – Endophage Jun 17 '13 at 15:52
  • I think You can iterate over `iteritems` and select value by key which satisfy your requirements. – oleg Jun 17 '13 at 15:54
  • As well as what @Pace has mentioned, is the trailing `,` also deliberate? – Jon Clements Jun 17 '13 at 15:54
  • @Progger ahhh okies - so simply, you just want to know how to access that in a Django template - the JSON data is actually well formed... – Jon Clements Jun 17 '13 at 15:55
  • 1
    @Progger have a look at http://stackoverflow.com/questions/8252387/how-do-i-access-dictionary-keys-that-contain-hyphens-from-within-a-django-templa – Jon Clements Jun 17 '13 at 15:59
  • 2
    @Progger Even if the data comes from a third-party, you must be passing it in via a `Context` at some point, so you ought to be able to translate `:id` to `id` at that point. – Aya Jun 17 '13 at 16:02
  • @JonClements has the crux of it. – Pace Jun 17 '13 at 16:28

3 Answers3

2

Your object is wrapped in an array.

obj = [
  {
    "street": "KEELER",
    ":id": 1421
  }
]

:id should be accessed like obj[0][':id'].

000
  • 26,951
  • 10
  • 71
  • 101
  • Ah, sorry. :( Django has some deep magic that I don't like very much. (I'm subscribed to the python list but not the django list) – 000 Jun 17 '13 at 16:25
1

So as @Aya recommended, what I did was dump the JSON to a string, replace all instances of ":id" with "id", then convert it back to JSON. At that point, I was able to access the ID like:

{{ obj.id }}
Progger
  • 2,266
  • 4
  • 27
  • 51
0

You could write your own parser and just parse the json as a string, there you can add custom parsing features to the id field. Although being in java, this might help

Community
  • 1
  • 1
David Karlsson
  • 9,396
  • 9
  • 58
  • 103