0

I have a JSON array shown below.

[
    "3D3iAR9M4HDETajfD79gs9BM8qhMSq5izX", 
    "35xfg4UnpEJeHDo55HNwJbr1V3G1ddCuVA"
]

I would like to add a value in the form of the string (self.tx_amount_5) so I get a JSON OBJECT something like this:

{
    "3D3iAR9M4HDETajfD79gs9BM8qhMSq5izX" : 100000
    "35xfg4UnpEJeHDo55HNwJbr1V3G1ddCuVA" : 100000
}

The part of code that has generated the first JSON array is:

r = requests.get('http://api.blockcypher.com/v1/btc/main/addrs/A/balance')
    balance = r.json()['balance']

    with open("Entries#x1.csv") as f,open("winningnumbers.csv") as nums:
        nums = set(imap(str.rstrip, nums))
        r = csv.reader(f)
        results = defaultdict(list)
        for row in r:
            results[sum(n in nums for n in islice(row, 1, None))].append(row[0])

    self.number_matched_0 = results[0]
    self.number_matched_1 = results[1]
    self.number_matched_2 = results[2]
    self.number_matched_3 = results[3]
    self.number_matched_4 = results[4]
    self.number_matched_5 = results[5]

    self.number_matched_5_json = json.dumps(self.number_matched_5, sort_keys = True, indent = 4)

    print(self.number_matched_5_json)

    if len(self.number_matched_3) == 0:
        print('Nobody matched 3 numbers')
    else:
        self.tx_amount_3 = int((balance*0.001)/ len(self.number_matched_3))

    if len(self.number_matched_4) == 0:
        print('Nobody matched 4 numbers')
    else:
        self.tx_amount_4 = int((balance*0.1)/ len(self.number_matched_4))

    if len(self.number_matched_5) == 0:
        print('Nobody matched 3 numbers')
    else:
        self.tx_amount_5 = int((balance*0.4)/ len(self.number_matched_5))
2
  • 2
    Can you specify what the problem is? Commented Oct 8, 2015 at 19:21
  • I essentially want to turn the first JSON array into the second JSON object Commented Oct 8, 2015 at 19:27

1 Answer 1

2

If I understand correctly, you can create the dictionary like this:

import json

s="""[
      "3D3iAR9M4HDETajfD79gs9BM8qhMSq5izX", 
      "35xfg4UnpEJeHDo55HNwJbr1V3G1ddCuVA"
]"""

d = {el: self.tx_amount_5 for el in json.loads(s)}
print(d)

which produces

{'3D3iAR9M4HDETajfD79gs9BM8qhMSq5izX': 100000,
 '35xfg4UnpEJeHDo55HNwJbr1V3G1ddCuVA': 100000}
Sign up to request clarification or add additional context in comments.

1 Comment

Please note that it's overkill to create a json and then parse it again. If it is possible to alter the code, create the dictionary alongside the json. BTW, the code has a cut&paste error in the error message for 5 numbers

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.