user2018860
user2018860

Reputation: 13

Python Parse JSON value with space delimited subfields

I need to parse JSON like this:

{
    "entity": " a=123455 b=234234 c=S d=CO e=1 f=user1 timestamp=null",
    "otherField": "text"
}

I want to get values for a, b, c, d, e, timestamp separately. Is there a better way than assigning the entity value to a string, then parsing with REGEX?

Upvotes: 1

Views: 1972

Answers (2)

James Sapam
James Sapam

Reputation: 16940

What about this:

>>> dic = dict(item.split("=") for item in s['entity'].strip().split(" "))
>>> dic 
>>> {'a': '123455', 'c': 'S', 'b': '234234', 'e': '1', 'd': 'CO', 'f': 'user1', 'timestamp':'null'}
>>> dic['a']
'123455'
>>> dic['b']
'234234'
>>> dic['c']
'S'
>>> dic['d']
'CO'
>>>

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1123930

There is nothing to the JSON standard that parses that value for you, you'll have to do this in Python.

It could be easier to just split that string on whitespace, then on =:

entities = dict(keyvalue.split('=', 1) for keyvalue in data['entity'].split())

This results in:

>>> data = {'entity': " a=123455 b=234234 c=S d=CO e=1 f=user1 timestamp=null"}
>>> dict(keyvalue.split('=', 1) for keyvalue in data['entity'].split())
{'a': '123455', 'c': 'S', 'b': '234234', 'e': '1', 'd': 'CO', 'f': 'user1', 'timestamp': 'null'}

Upvotes: 2

Related Questions