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
3
  • 3
    Possible duplicate of String to Dictionary in Python Commented Sep 14, 2018 at 8: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. Commented Sep 14, 2018 at 8:16
  • Is this the response from a http request made using requests library ? Commented Sep 14, 2018 at 8:32

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Got it thanks print("Active Users:"),d['cardinality']
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'
>>> 

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.