2
test=[]
sites = sel.css(".info")
for site in sites:
    money = site.xpath("./h2[@class='money']/text()").extract()
    people = site.xpath("//p[@class='poeple']/text()").extract()
    test.append('{"money":'+str(money[0])+',"people":'+str(people[0])+'}')        

My result test is:

['{"money":1,"people":23}', 
  '{"money":3,"people":21}', 
  '{"money":12,"people":82}', 
  '{"money":1,"people":54}' ]

I was stuck by two thing:

One is I print the type of test is string,so is not like JSON format

Two is the money value with 1 is duplicate,so I need to add the people together ,
so the final format I want is:

[
{"money":1,"people":77},
{"money":3,"people":21},
{"money":12,"people":82},
]

How can I do this??

0

2 Answers 2

1

I'd collect money entries in a dict and add up the people as values, the output to json should be done using a json library indeed (I've not tested the code but it should give you an idea how you can approach the problem):

money_map = {}
sites = sel.css(".info")
for site in sites:
    money = site.xpath("./h2[@class='money']/text()").extract()[0]
    people = int(site.xpath("//p[@class='poeple']/text()").extract()[0])
    if money not in money_map:
        money_map[money] = 0

    money_map[money] += people

import json
output = [{'money': key, 'people': value} for key, value in money_map.items()]
json_output = json.dumps(output)
Sign up to request clarification or add additional context in comments.

Comments

0

basically this:

import json
foo = ['{"money":1,"people":23}',
  '{"money":3,"people":21}',
  '{"money":12,"people":82}',
  '{"money":1,"people":54}' ]


bar = []
for i in foo:
    j = json.loads(i) # string to json/dict
    # if j['money'] is not in bar:
    bar.append(j)
    # else:
    # find index of duplicate and add j['people']

Above is incomplete solution, you have to implement the 'duplicate check and add'

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.