0

Below is the output stored in str variable, I want to extract the cardinality value of whatever it is, I have extracted it using simple way print str[15:18] but every time I have to change the string value if cardinality value going to increase or decrease.

Output:

{"cardinality":483,"timestamp":15369087280,"deltas":{"week_over_week":{"delta_fraction":0.047722318876,"last_week_value":146}}}

Stored in str:

str = response.text

Expected Output:

Active: 483
blaCkninJa
  • 445
  • 2
  • 11
  • 22
  • 3
    Possible duplicate of [String to Dictionary in Python](https://stackoverflow.com/questions/4917006/string-to-dictionary-in-python) – SiHa Sep 14 '18 at 08:04
  • Your string is either json content or the string representation of a python dict. Depending on which it is (where does it come from ?), you want to use either `json.loads()` or `ast.literal_eval()` to deserialize it to a python dict, then you just have to get the value from the `"cardinality"` key. – bruno desthuilliers Sep 14 '18 at 08:16
  • Is this the response from a http request made using `requests` library ? – Vishvajit Pathak Sep 14 '18 at 08:32

3 Answers3

3

You can pass your string as JSON to get a dictionary, and then simply read out the value:

import json
s = '{"cardinality": 483, "timestamp": 15369087280, "deltas": {"week_over_week": {"delta_fraction": 0.047722318876, "last_week_value": 146}}}'
d = json.loads(s)
print(d['cardinality'])
# 483
101
  • 8,514
  • 6
  • 43
  • 69
1

Use ast:

>>> s='{"cardinality":483,"timestamp":15369087280,"deltas":{"week_over_week":{"delta_fraction":0.047722318876,"last_week_value":146}}}'
>>> import ast
>>> 'Active: %s'%ast.literal_eval(s)['cardinality']
'Active: 483'
>>> 

As @101 said also able to use json.loads:

>>> import json
>>> s='{"cardinality":483,"timestamp":15369087280,"deltas":{"week_over_week":{"delta_fraction":0.047722318876,"last_week_value":146}}}'
>>> 'Active: %s'%json.loads(s)['cardinality']
'Active: 483'
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

There are 2 ways :

1.

In [10]: import ast
In [11]: s='{"cardinality":483,"timestamp":15369087280,"deltas":{"week_over_week":{"delta_fraction":0.047722318876,"last_week_value":146}}}'
In [12]: ast.literal_eval(s)
In [13]: %timeit ast.literal_eval(s)['cardinality']
10000 loops, best of 3: 29.4 µs per loop

2.

In [14]: import json
In [15]: s='{"cardinality":483,"timestamp":15369087280,"deltas":{"week_over_week":{"delta_fraction":0.047722318876,"last_week_value":146}}}'
In [16]: %timeit json.loads(s)['cardinality']
100000 loops, best of 3: 5.73 µs per loop

So you should use json as its relatively faster than ast

Vishvajit Pathak
  • 3,351
  • 1
  • 21
  • 16