0

If I have a json file with multiple json objects such as following

{"created_at":"Sun Apr 16 02:00:14 +0000 2017","id":853427785339084800,"id_str":"853427785339084800"}

{"created_at":"Sun Apr 16 02:03:24 +0000 2017","id":853428582613475332,"id_str":"853428582613475332"}

I want to loop all the json objects add add new element together with value through user input in command line one by one. Is it possible because my format not in json array?

import json
import pandas as pd
from pprint import pprint

tweets_data_path = 'data.json'

tweets_data = []
tweets_file = open(tweets_data_path, "r")
for line in tweets_file:
    try:
        tweet = json.loads(line)
        tweets_data.append(tweet)
    except:
        continue

pprint(tweets_data)
0

1 Answer 1

2

Your code runs fine, so I am assuming the question is on how to add user input as a new key-value pair for each json you load from the file. For python 2.7 use raw_input, for python 3 raw_input was renamed to input.

import json
import pandas as pd
from pprint import pprint

tweets_data_path = 'data.json'

tweets_data = []
tweets_file = open(tweets_data_path, "r")
for line in tweets_file:
    try:
        tweet = json.loads(line)
        tweet["new_key"] = raw_input('provide input: ')
        tweets_data.append(tweet)
    except:
        continue

pprint(tweets_data)
Sign up to request clarification or add additional context in comments.

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.